Swift - 元类型 .Type 和 .self 有什么区别? [英] Swift - what's the difference between metatype .Type and .self?

查看:73
本文介绍了Swift - 元类型 .Type 和 .self 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 中的元类型 .Type.self 有什么区别?

What's the difference between metatype .Type and .self in Swift?

.self.Type 会返回一个 struct 吗?

Do .self and .Type return a struct?

我知道 .self 可用于检查 dynamicType.你如何使用.Type?

I understand that .self can be used to check with dynamicType. How do you use .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

假设每个实体由两件事表示:

Let's say that each entity is represented by two things:

  • 类型:#实体名称#

元类型:# entity name # .Type

元类型是指任何类型的类型,包括类类型、结构类型、枚举类型和协议类型.

A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.

来源.

您很快就会注意到这是递归的,并且可以通过 (((T.Type).Type).Type) 等类型.

You can quickly notice that this is recursive and there can by types like (((T.Type).Type).Type) and so on.

.Type 返回一个元类型的实例.

.Type returns an instance of a metatype.

有两种方法可以获得元类型的实例:

There are two ways we can get an instance of a metatype:

  • 在像 Int.self 这样的具体类型上调用 .self 这将创建一个static 元类型实例 Int.Type.

  • Call .self on a concrete type like Int.self which will create a static metatype instance Int.Type.

从任何实例获取动态元类型实例type(of: someInstance).

Get the dynamic metatype instance from any instance through 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.这会阻止所有通用算法与协议元类型一起工作,并可能导致运行时崩溃.

.Protocol is yet another metatype which only exisits in context of protocols. That said, there is no way how we can express that we want only P.Type. This prevents all generic algorithms to work with protocol metatypes and can lead to runtime crashes.

对于更多好奇的人:

type(of:) 函数实际上是由编译器处理的,因为.Protocol 创建了不一致.

The type(of:) function is actually handled by the compiler because of the inconsistency .Protocol creates.

// 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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆