Swift-元类型.Type和.self有什么区别?
元类型.Type和.selfSwift中有什么区别?
这样做.self并.Type返回一个struct?
我了解.self可以用来进行检查dynamicType。你怎么用.Type?
回答:
这是一个简单的示例:
func printType<T>(of type: T.Type) {    // or you could do "\(T.self)" directly and
    // replace `type` parameter with an underscore
    print("\(type)") 
}
printType(of: Int.self) // this should print Swift.Int
func printInstanceDescription<T>(of instance: T) {
    print("\(instance)")
}
printInstanceDescription(of: 42) // this should print 42
假设每个实体由两件事表示:
- 类型: - # entitiy name #
- 元类型: - # entity name # .Type
元类型类型是指任何类型的类型,包括类类型,结构类型,枚举类型和协议类型。
资源。
您会很快注意到这是递归的,并且可以通过诸如此类的类型(((T.Type).Type).Type)来实现。
.Type 返回一个元类型的实例。
我们可以通过两种方式获取元类型的实例:
- 调用 - .self一个像- Int.self这样的具体类型,它将创建一个 类型实例- Int.Type。
- 通过从任何实例获取 类型实例 - type(of: someInstance)。
危险区域:
struct S {}protocol P {}
print("\(type(of: S.self))")      // S.Type
print("\(type(of: S.Type.self))") // S.Type.Type
print("\(type(of: P.self))")      // P.Protocol
print("\(type(of: P.Type.self))") // P.Type.Protocol
.Protocol是另一个仅在协议环境中存在的元类型。就是说,我们无法表达只想要的东西P.Type。这会阻止所有通用算法与协议元类型一起使用,并可能导致运行时崩溃。
对于更多好奇的人:
type(of:)由于.Protocol创建的不一致,该函数实际上由编译器处理。
// This implementation is never used, since calls to `Swift.type(of:)` are// resolved as a special case by the type checker.
public func type<T, Metatype>(of value: T) -> Metatype { ... }
以上是 Swift-元类型.Type和.self有什么区别? 的全部内容, 来源链接: utcz.com/qa/423250.html






