Swift 元类型(类型,自我) [英] Swift metatype (Type, self)
问题描述
我试图理解:self, dynamicType, Type
".我有这个代码:
I am trying to understand : "self, dynamicType, Type
". I have this code :
class SomeClass {}
let cls : SomeClass.Type = SomeClass.self
let cls2 : SomeClass = SomeClass()
cls
和 cls2
是一回事吗?
有人可以提供一些有关差异的详细信息吗?谢谢
Can someone give some detail about the differences ? Thanks
推荐答案
不,cls
和 cls2
是不同的东西.理解差异的最简单方法是像这样扩展您的示例:
No, cls
and cls2
are different things. The easiest way to understand the difference will be to extend your example like this:
class SomeClass {
class func doIt() {
print("I'm a class method. I belong to my type.")
}
func doItOnlyIfInstanceOfThisType() {
print("I'm a instance method. I belong to my type instance.")
}
}
现在让我们来看看你的 cls
:
And now let's take your cls
:
let cls : SomeClass.Type = SomeClass.self
cls.doIt()
这将打印 I'm a class method.我属于我的类型.
.但是你不能调用这个:
That will print I'm a class method. I belong to my type.
. But you cannot invoke this:
cls.doItOnlyIfInstanceOfThisType() // causes a compilation error, PRO TIP: actually you can use this method as a func property, but I'll add the explanation for this later
让我们使用您的 cls2
.它唯一可见的方法是 doItOnlyIfInstanceOfThisType
因为它是一个实例方法(这种类型).
Let's take your cls2
. The only visible method of it is doItOnlyIfInstanceOfThisType
because it's an instance method (of this type).
let cls2 : SomeClass = SomeClass()
cls2.doItOnlyIfInstanceOfThisType()
所以它们的区别在于cls
是一个类型,cls2
是这个类型的一个实例.
So the difference between them is that cls
is a type and cls2
is an instance of this type.
多一点关于为什么 SomeClass.self 和 SomeClass() 的知识?
类的类型也存在于内存中(例如它有自己的方法),作为代表类型的单例(不是这种类型的实例 - 这是不同的东西).如果你在像这样的 SomeClass.self
这样的类型上调用 self
你将得到一个代表 SomeClass
类型的单例实例.
The type of a class also exists in memory (it has for example its own methods), as a singleton representing the Type (not an instance of this type - that's something different).
If you call self
on a Type like this SomeClass.self
you will get a singleton instance representing the SomeClass
Type.
SomeClass()
调用 SomeClass
的 init()
方法,这是一个创建 SomeClass
.
SomeClass()
invokes the init()
method of SomeClass
, a constructor that creates an instance of SomeClass
.
专业提示
您可以操作 Type 实例函数(如 ObjC 中的闭包/块).这是一个生成的类方法.但是您必须传递一个您从中获取此方法的类型的实例作为参数,如下所示:
You can manipulate a Type instance function (like closures/blocks in ObjC). It's a generated class method. But you must pass an instance of the type that you take this method from as an argument, like this:
let myFunc :()->() = cls.doItOnlyIfInstanceOfThisType(cls2)
myFunc()
这篇关于Swift 元类型(类型,自我)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!