zumzum
zumzum

Reputation: 20158

Swift generic array to specific type

I am writing a function that needs to return an array of items. In the function there will be some logic that will determine the type of the items I want to return from the function. I started something like this:

func testFunc<T>(option:Int) -> [T] {
    var result:[T] = []

    switch option {
    case 1:
        let sampleString:String = "hello"
        result.append(sampleString)
    case 2:
        let sampleInt:Int = 23
        result.append(sampleInt)
    default:
        return result
    }

    return result
}

This gives me the following errors:

"cannot invoke append with an argument list of type '(String)', 
and 
"cannot invoke append with an argument list of type '(Int)'

It makes sense, but, I am trying to figure out how to solve my problem. When I call the function I don't know what type will be in the array returned, but the function will know how to determine the type before it start appending items to the array.

How can I accomplish this in Swift?

Upvotes: 0

Views: 2667

Answers (1)

Palle
Palle

Reputation: 12109

Swift does not support variables with multiple types. Using a generic T makes the function generic so the return type can be chosen by the caller. You should rethink your design.

If you really want to return multiple result types based on a parameter, there are a few workarounds:

1: Use an Any array.

var result:[Any] = []

2: Use an enum with associated values

enum TestFuncResult {
    case string(String)
    case int(Int)
}

func testFunc(option: Int) -> [TestFuncResult] {
    var result:[TestFuncResult] = []

    switch option {
    case 1:
        let sampleString:String = "hello"
        result.append(.string(sampleString))
    case 2:
        let sampleInt:Int = 23
        result.append(.int(sampleInt))
    default:
        return result
    }

    return result
}

Upvotes: 6

Related Questions