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)
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.
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.
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?
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With