rogueleaderr
rogueleaderr

Reputation: 4819

Returning literal values from Swift generic function?

I would like to create a function that can return an array of one of several different types, depending on the type it's parameterized with. The twist is that I would like to specify the return values as literals. Is there a way to do this (or something analogous to this?) It should look something like this:

func values<T>() -> [T] {
    switch T.self {
        case is String.Type:
            return ["A", "B", "C"]
        default:
            return []
    }
}

That specific code produces this error on the return line: "Cannot convert return expression of type '[String]' to return type '[T]'"

The reason I care is because I'm trying to create a generic view controller that has a sections variable (or function) where the sections are elements from an enum. But I want to use different enums depending on the on the type the class is parameterized with.

Upvotes: 0

Views: 118

Answers (1)

Rob Napier
Rob Napier

Reputation: 299565

You're describing overloading:

func values() -> [String] {
    return ["A", "B", "C"]
}

func values() -> [Int] {
    return [1,2,3]
}

In many cases, however, return-type overloading turns out to be very inconvenient because you have to use too many explicit types, but by your description, this should work fine.

Upvotes: 2

Related Questions