gpt4 book ai didi

swift - “Self”不能用于非平凡闭包

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:30 24 4
gpt4 key购买 nike

我想要一个带有静态初始化方法的类:

class A {

required init() {
}

// this one works
class func f0() -> Self {
return self.init()
}

// this one works as well
class func f1() -> Self {
let create = { self.init() } // no error, inferred closure type is '() -> Self'
return create()
}
}

不幸的是,Swift 3 编译器无法为任何比 { self.init() } 更复杂的闭包推断类型。例如:

class func f2() -> Self {
let create = {
// error: unable to infer complex closure return type; add explicit type to disambiguate
let a = self.init()
return a
}

return create()
}

任何明确指定闭包类型、变量类型或从 A 转换为 Self 的尝试都会导致错误:

class func f3() -> Self {
let create = { () -> Self in // error: 'Self' is only available in a protocol or as the result of a method in a class;
let a = self.init()
return a
}

return create()
}

class func f4() -> Self {
let create = {
let a: Self = self.init() // error: 'Self' is only available in a protocol or as the result of a method in a class;
return a
}

return create()
}

class func f5() -> Self {
let create = { () -> A in
let a = self.init()
return a
}

return create() as! Self // error: cannot convert return expression of type 'A' to return type 'Self'
}

解决方案是使用 Self 避免闭包。

这似乎是编译器的一个非常不幸的限制。这背后有什么原因吗?这个问题可能会在未来的 Swift 版本中得到解决吗?

最佳答案

根本的问题是,Swift 需要在编译时确定 Self 的类型,而你想在运行时确定它。如果一切都可以在编译时解决,它已经有所扩展,允许类函数返回 Self,但 Swift 不能总是证明你的类型在某些情况下必须是正确的(有时因为它还不知道如何,有时是因为实际上可能是错误的)。

例如,考虑一个不重写自返回方法的子类。它如何返回子类?如果它将 Self 传递给其他东西怎么办?给定编译器甚至不知道的 future 子类,您如何在编译时进行静态类型检查? (包括可以在运行时和跨模块边界添加的子类。)

我希望这会变得更好一些,但是 Swift 不鼓励这种复杂的继承(这些是非最终类,所以你必须考虑所有可能的子类)并且更喜欢长期的协议(protocol),所以我不期望这在 Swift 4 或 5 中是完全可能的。

关于swift - “Self”不能用于非平凡闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573825/

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