Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set type of generic T return in swift

Tags:

swift

swift3

For a given generic function

func myGenericFunction<T>() -> T { }

I can set what class that generic will be with

let _:Bool = myGenericFunction()

is there a way to do this so I don't have to define a variable separately on another line?

ex: anotherFunction(myGenericFunction():Bool)

like image 203
wyu Avatar asked Oct 10 '16 20:10

wyu


People also ask

Can you have a generic type in Swift?

In addition to generic functions, Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary. This section shows you how to write a generic collection type called Stack.

Why can’t I call swaptwovalues () in Swift?

Because T is a placeholder, Swift doesn’t look for an actual type called T. The swapTwoValues (_:_:) function can now be called in the same way as swapTwoInts, except that it can be passed two values of any type, as long as both of those values are of the same type as each other.

What is a generic array in Swift?

Swift array uses the concept of generics. For example, Here, list1 array that holds Int values and list2 array that holds String values. Similar to arrays, dictionaries are also generic in Swift. Did you find this article helpful?

What does item = int mean in Swift?

The definition of typealias Item = Int turns the abstract type of Item into a concrete type of Int for this implementation of the Container protocol. Thanks to Swift’s type inference, you don’t actually need to declare a concrete Item of Int as part of the definition of IntStack.


1 Answers

The compiler needs some context to infer the type T. In a variable assignment, this can be done with a type annotation or a cast:

let foo: Bool = myGenericFunction()
let bar = myGenericFunction() as Bool

If anotherFunction takes a Bool parameter then

anotherFunction(myGenericFunction())

just works, T is then inferred from the parameter type.

If anotherFunction takes a generic parameter then the cast works again:

anotherFunction(myGenericFunction() as Bool)

A different approach would be to pass the type as an argument instead:

func myGenericFunction<T>(_ type: T.Type) -> T { ... }

let foo = myGenericFunction(Bool.self)
anotherFunction(myGenericFunction(Bool.self))
like image 95
Martin R Avatar answered Oct 19 '22 03:10

Martin R