gpt4 book ai didi

swift - 在什么情况下可以使用下面描述的方法?谁能提供一些有用的例子?

转载 作者:可可西里 更新时间:2023-11-01 01:36:59 25 4
gpt4 key购买 nike

我在一段源码中找到了下面的方法,我无法理解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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com