Swift: 传递类型作为参数

Swift: Pass Type as Parameter

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

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

当然,t 作为类型传入,但我想传入 Type 本身,以便我可以在函数体中检查该类型。

您可以使用 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
}

示例用法:

[1,2, 3] <-? NSArray.self // Prints {[1, 2, 3]}
[1,2, 3] <-? NSDictionary.self // Prints nil