您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Swift-元类型.Type和.self有什么区别?

Swift-元类型.Type和.self有什么区别?

这是一个简单的示例:

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 2022/1/1 18:16:09 有357人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶