加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift:Self.init在初始化程序中多次调用

发布时间:2020-12-14 02:24:25 所属栏目:百科 来源:网络整理
导读:这个让我难过.我无法弄清楚为什么 Swift抱怨self.init在这段代码中不止一次被调用: public init(body: String) { let parser = Gravl.Parser() if let node = parser.parse(body) { super.init(document: self,gravlNode: node) } else { // Swift complain
这个让我难过.我无法弄清楚为什么 Swift抱怨self.init在这段代码中不止一次被调用:
public init(body: String) {
    let parser = Gravl.Parser()

    if let node = parser.parse(body) {
        super.init(document: self,gravlNode: node)
    } else {
        // Swift complains with the mentioned error on this line (it doesn't matter what "whatever" is):
        super.init(document: self,gravlNode: whatever)
    }
}

除非我遗漏了某些内容,否则很明显它只会调用init一次.有趣的是,如果我评论第二行,Swift抱怨所有路径都没有调用Super.init,哈哈.

我错过了什么?

更新:

好的,所以问题肯定是在调用super.init时尝试传递self.哈,我完全忘了我在做那件事.我想我已经通过实验编写并编译并认为它可能确实有效,但看起来像it’s actually a bug它完全按照这种方式编译.

无论如何,因为将self传递给初始化器是一种多余的,因为它是同一个对象,我将父初始化器更改为接受一个可选的文档参数(它只是一个内部初始化器,所以没什么大不了的),如果它没有,我只是将它设置为自我在父初始化程序中.

对于那些好奇的人来说,这就是父初始化程序(现在)的样子:

internal init(document: Document?,gravlNode: Gravl.Node) {
    self.value = gravlNode.value
    super.init()
    self.document = document ?? self as! Document
    // other stuff...
}
我怀疑这是一个错误的诊断(即错误的错误消息).如果你有一个我们可以试验的完整例子会非常有用,但是这条线没有意义(我怀疑是潜在的问题):
super.init(document: self,gravlNode: node)

你不能把自己传递给super.init.你还没有初始化(直到你调用super.init才初始化).例如,请考虑以下简化代码:

class S {
    init(document: AnyObject) {}
}

class C: S {
    public init() {
        super.init(document: self)
    }
}

这会导致错误:在super.init调用之前使用’self’,我认为这是正确的错误.

编辑:我相信Hamish肯定发现了编译器错误.您可以在Xcode 8.3.1中以这种方式利用它(尚未在8.3.2上测试过):

class S {
    var x: Int
    init(document: S) {
        self.x = document.x
    }
}

class C: S {
    public init() {
        super.init(document: self)
    }
}

let c = C() // malloc: *** error for object 0x600000031244: Invalid pointer dequeued from free list

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读