Is it possible to pass in a Type as a function parameter in Swift? Note: I do not want to pass in an object of the specified type, but instead the Type itself. For example, if I wanted to replicate Swift's as?
functionality:
infix operator <-? { associativity left }
func <-? <U,T>(x:U?, t:T) -> T? {
if let z = x as? t {
return z
}
}
}
Of course, t
is being pass in as a type, but I would like to pass in the Type itself so I can check against that type in the function body.
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.
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.
In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass .
In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.
You can use T.Type
, but you have to cast as T
and not t
:
infix operator <-? { associativity left }
func <-? <U,T>(x:U?, t:T.Type) -> T? {
if let z = x as? T {
return z
}
return nil
}
Sample usage:
[1,2, 3] <-? NSArray.self // Prints {[1, 2, 3]}
[1,2, 3] <-? NSDictionary.self // Prints nil
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