Reputation: 3952
When working with Swift Generics, do the type placeholders all have to be the same types? The example below turns all type placeholders into a string type. Is it possible for the parameter to be a string and the return type be an Int or do Generics work where each placeholder is the of the same type?
Here's the example:
func takeAndReturnSameThing<T>(t: T) -> T {
return t
}
Let thing = takeAndReturnSameThing("howdy")
Upvotes: 1
Views: 1114
Reputation:
You can have multiple generic types like this:
func takeAndReturnDifferentThing<T,U>(t:T) -> U {
return t.convertToU() // Assuming type T has this method.
}
Of course you should constrain both T and S to make sure that T can be converted to S.
Upvotes: 3
Reputation: 63359
The whole point of type parameters ("place holders") is that they consistently represent the same type.
If you want to represent multiple types generically, you introduce new type parameters.
func takeAndReturnADifferentThing<T, U>(t: T) -> U {
return t.getU()
}
Upvotes: 3