Laurence Wingo
Laurence Wingo

Reputation: 3952

Swift Generic parameters and return types

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

Answers (2)

user887210
user887210

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

Alexander
Alexander

Reputation: 63359

Yes

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

Related Questions