我在部分源代码中发现了以下方法,我无法理解Self.Type
之间的区别和Self.Type.Type
property SomeProperty {
static func type() -> Self.Type.Type {
return self.dynamicType
}
}
也许有人可以给我一些见解?
上面的代码片段来自以下扩展:
extension Property {
static func size() -> Int {
return Int(ceil(Double(sizeof(self))/Double(sizeof(Int))))
}
static func type() -> Self.Type.Type { return self.dynamicType }
mutating func codeInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as
UnsafeMutablePointer<Self>).memory = self
}
mutating func codeOptionalInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as
UnsafeMutablePointer<Optional<Self>>).memory = self
}
}
最佳答案
我怀疑原作者误解了 static
如何与 self
和子类一起使用。他们最初可能是这样写的,打算返回“这个特定子类的类型:”
protocol TypeReturning {}
extension TypeReturning {
static func type() -> Self.Type {
return self.dynamicType
}
}
错误在于dynamicType
在这里并没有真正的意义。由于static
上下文,self
是动态类型。但作者会收到错误:
error: cannot convert return expression of type 'Self.Type.Type' to return type 'Self.Type'
我假设他们读到该错误并想“啊!我的返回类型错误”,然后他们修复了它:
static func type() -> Self.Type.Type {
return self.dynamicType
}
正确的解决方案是:
static func type() -> Self.Type {
return self
}
尽管更好的解决方案可能是完全避免这种情况;这是一个不必要的功能。它们只是指 SomeClass.self
并且应该这样写。
.Type.Type
是有意义的。它是一个元类型(类型本身的类型)。但我不知道你实际上可以用它做什么。在 Swift 中,类型不是第一类对象。
关于swift - 下面描述的方法可以在什么情况下使用?谁能提供一些有用的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011970/