Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Pass Type as Parameter

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.

like image 831
Aaron Hayman Avatar asked Jan 23 '15 18:01

Aaron Hayman


People also ask

Can we pass function as a parameter in Swift?

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.

What is Inout in Swift?

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.

What is .type Swift?

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 .

What is Variadic parameters in Swift?

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.


1 Answers

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
like image 192
Antonio Avatar answered Sep 22 '22 05:09

Antonio