0

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?

2
  • The type checker doesn't know about switches; it's not able to figure out what T will be based on the value of option. Is there a reason that you can't break this into two functions? Commented Aug 28, 2016 at 0:37
  • If the return type it is not related to the input type just return an Array of Any Swift 3 or AnyObject Swift 2 Commented Aug 28, 2016 at 0:38

1 Answer 1

6

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.