gpt4 book ai didi

swift - 协议(protocol)/POP 问题 : error: 'self' used before chaining to another self. 初始化要求:

转载 作者:搜寻专家 更新时间:2023-11-01 07:14:47 24 4
gpt4 key购买 nike

尝试在类初始化期间使用此函数,这样我就可以将类型名称自动添加到标题中:

func getTypeOf(_ object: Any) -> String {  
return String(describing: type(of: object)) + ": "
}

我让它在典型的继承设置中运行良好,但我正在努力切换到更多的 POP/FP 风格:

import SpriteKit

//
// OOP Demo:
//
class IGEoop: SKSpriteNode {

init(title: String) {
super.init(texture: nil, color: UIColor.blue, size: CGSize.zero)
self.name = getTypeOf(self) + title
}
required init?(coder aDecoder: NSCoder) { fatalError() }
}

class PromptOOP: IGEoop {
}

// Works fine:
let zipOOP = PromptOOP(title: "hi oop")
print(zipOOP.name!)

这是我无法工作的 block ,并收到错误消息:

error: 'self' used before chaining to another self.init requirement:

//
// POP Demo:
//
protocol IGEpop { init(title: String) }
extension IGEpop where Self: SKSpriteNode {
init(title: String) {
// error: 'self' used before chaining to another self.init requirement:
self.name = getTypeOf(self) + title
}
}

class PromptPOP: SKSpriteNode, IGEpop {
required init?(coder aDecoder: NSCoder) { fatalError() }
}

// Errars:
let zipPOP = PromptOOP(title: "hi pop")
print(zipPOP.name!)

感谢任何解决方案或解决方法!

最佳答案

就像在您的继承示例中一样,您需要链接到另一个初始化程序才能使用 self。因此,例如,我们可以链接到 init(texture:color:size):

extension IGEpop where Self : SKSpriteNode {

init(title: String) {
self.init(texture: nil, color: .blue, size: .zero)
self.name = getTypeOf(self) + title
}
}

唯一的问题是 PromptPOP 没有init(texture:color:size) 的实现。它定义了指定初始化器init(aCoder:)的实现,因此它不继承SKSpriteNode的指定初始化器。

因此,您需要删除 init(aCoder:) 的实现,以便 PromptPOP 可以继承其父类(super class)的指定初始化器,或者提供 的实现init(texture:color:size)——在这种情况下可以简单地链接到super:

class PromptPOP : SKSpriteNode, IGEpop {
required init?(coder aDecoder: NSCoder) { fatalError() }

// note that I've marked the initialiser as being required, therefore ensuring
// that it's available to call on any subclasses of PromptPOP.
override required init(texture: SKTexture?, color: NSColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
}

虽然可能值得将您在协议(protocol)扩展中使用的初始化程序添加到协议(protocol)要求中,从而确保所有符合标准的类型在编译时实现它(否则如果他们没有)。

protocol IGEpop {
init(title: String)
init(texture: SKTexture?, color: NSColor, size: CGSize)
}

关于swift - 协议(protocol)/POP 问题 : error: 'self' used before chaining to another self. 初始化要求:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42775934/

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