I'd like to do something like this:
func doSomething(a: AnyObject, myType: ????) { if let a = a as? myType { //… } }
In Objective-C the class of class was Class
To pass function as parameter to another function in Swift, declare the parameter to receive a function with specific parameters and return type. The syntax to declare the parameter that can accept a function is same as that of declaring a variable to store a function.
A type parameter is simply the name of a placeholder type (for example, T , U , V , Key , Value , and so on). You have access to the type parameters (and any of their associated types) in the rest of the type, function, or initializer declaration, including in the signature of the function or initializer.
Swift inout parameter is a parameter that can be changed inside the function where it's passed into. To accept inout parameters, use the inout keyword in front of an argument. To pass a variable as an inout parameter, use the & operator in front of the parameter.
Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.
You have to use a generic function where the parameter is only used for type information so you cast it to T
:
func doSomething<T>(_ a: Any, myType: T.Type) { if let a = a as? T { //… } } // usage doSomething("Hello World", myType: String.self)
T
You don’t know the signature of T
in general because T
can be any type. So you have to specify the signature in a protocol.
For example:
protocol IntInitializable { init(value: Int) }
With this protocol you could then write
func numberFactory<T: IntInitializable>(value: Int, numberType: T.Type) -> T { return T.init(value: value) } // usage numberFactory(value: 4, numberType: MyNumber.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