如何在 Swift 中将类型别名作为函数参数传递?
How can I pass a typealias as a function parameter in Swift?
是否可以在 Swift 中将 typealias
作为函数参数传递?
我想做类似的事情:
func doSomethingWithType(type: typealias)
A type alias declaration introduces a named alias of an existing type
into your program. Type alias declarations are declared using the
keyword typealias and have the following form:
typealias name = existing type
After a type alias is declared, the aliased name can be used instead
of the existing type everywhere in your program. The existing type can
be a named type or a compound type. Type aliases do not create new
types; they simply allow a name to refer to an existing type.
所以你可以这样使用它:
typealias yourType = String
func doSomethingWithType(type: yourType) {
}
类型别名只是现有类型的同义词 - 它不会创建新类型,它只是创建一个新名称。
也就是说,如果要将类型传递给函数,可以将其设为泛型,并按如下方式定义:
func doSomething<T>(type: T.Type) {
println(type)
}
您可以通过传递类型来调用它 - 例如:
doSomething(String.self)
这将打印
"Swift.String"
如果您为 String
定义类型别名,输出将不会改变:
typealias MyString = String
doSomething(MyString.self)
是否可以在 Swift 中将 typealias
作为函数参数传递?
我想做类似的事情:
func doSomethingWithType(type: typealias)
A type alias declaration introduces a named alias of an existing type into your program. Type alias declarations are declared using the keyword typealias and have the following form:
typealias name = existing type
After a type alias is declared, the aliased name can be used instead of the existing type everywhere in your program. The existing type can be a named type or a compound type. Type aliases do not create new types; they simply allow a name to refer to an existing type.
所以你可以这样使用它:
typealias yourType = String
func doSomethingWithType(type: yourType) {
}
类型别名只是现有类型的同义词 - 它不会创建新类型,它只是创建一个新名称。
也就是说,如果要将类型传递给函数,可以将其设为泛型,并按如下方式定义:
func doSomething<T>(type: T.Type) {
println(type)
}
您可以通过传递类型来调用它 - 例如:
doSomething(String.self)
这将打印
"Swift.String"
如果您为 String
定义类型别名,输出将不会改变:
typealias MyString = String
doSomething(MyString.self)