如何将 Swift 类型作为方法参数传递?
How to pass a Swift type as a method argument?
我想做这样的事情:
func doSomething(a: AnyObject, myType: ????)
{
if let a = a as? myType
{
//…
}
}
在 Objective-C 中 class 的 class 是 Class
您必须使用参数仅用于类型信息的通用函数,因此您将其转换为 T
:
func doSomething<T>(_ a: Any, myType: T.Type) {
if let a = a as? T {
//…
}
}
// usage
doSomething("Hello World", myType: String.self)
使用 T
类型的初始值设定项
你一般不知道T
的签名,因为T
可以是任何类型。所以你必须在协议中指定签名。
例如:
protocol IntInitializable {
init(value: Int)
}
使用此协议,您可以编写
func numberFactory<T: IntInitializable>(value: Int, numberType: T.Type) -> T {
return T.init(value: value)
}
// usage
numberFactory(value: 4, numberType: MyNumber.self)
我想做这样的事情:
func doSomething(a: AnyObject, myType: ????)
{
if let a = a as? myType
{
//…
}
}
在 Objective-C 中 class 的 class 是 Class
您必须使用参数仅用于类型信息的通用函数,因此您将其转换为 T
:
func doSomething<T>(_ a: Any, myType: T.Type) {
if let a = a as? T {
//…
}
}
// usage
doSomething("Hello World", myType: String.self)
使用 T
类型的初始值设定项
你一般不知道T
的签名,因为T
可以是任何类型。所以你必须在协议中指定签名。
例如:
protocol IntInitializable {
init(value: Int)
}
使用此协议,您可以编写
func numberFactory<T: IntInitializable>(value: Int, numberType: T.Type) -> T {
return T.init(value: value)
}
// usage
numberFactory(value: 4, numberType: MyNumber.self)