Swift:传递类型作为参数

Aar*_*man 14 types functional-programming swift

是否可以在Swift中传入Type作为函数参数?注意:我不想传入指定类型的对象,而是传递Type本身.例如,如果我想复制Swift的as?功能:

infix operator <-? { associativity left }
func <-? <U,T>(x:U?, t:T) -> T? {
  if let z = x as? t {
      return z
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,t作为一个类型传入,但我想传递Type本身,所以我可以在函数体中检查该类型.

Ant*_*nio 18

你可以使用T.Type,但是你必须投射T而不是t:

infix operator <-? { associativity left }
func <-? <U,T>(x:U?, t:T.Type) -> T? {
    if let z = x as? T {
        return z
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

[1,2, 3] <-? NSArray.self // Prints {[1, 2, 3]}
[1,2, 3] <-? NSDictionary.self // Prints nil
Run Code Online (Sandbox Code Playgroud)