是否可以在Swift中传递Type作为函数参数?注意:我不想传入指定类型的对象,而是传入类型本身。例如,如果我想复制Swift的 as? 功能:
as?
infix operator <-? { associativity left } func <-? <U,T>(x:U?, t:T) -> T? { if let z = x as? t { return z } } }
当然 t 正在作为类型传入,但我希望传入类型本身,以便可以在函数体中检查该类型。
t
您可以使用 T.Type 但你必须扮演 T 而不是 t :
T.Type
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