简体   繁体   English

将自己作为自己的初始化程序中的委托传递给初始化程序

[英]Passing self into initializer as delegate within own initializer

might be a silly question, but I'm trying to understand better why I can't do this.可能是一个愚蠢的问题,但我试图更好地理解为什么我不能这样做。 I recall this working in Swift 5.6.1, but I recently updated to Swift 5.7.2.我记得这个在 Swift 5.6.1 中工作,但我最近更新到 Swift 5.7.2。

Before asking, I want to note that I did see this question: Swift passing self as argument in class init , but it didn't quite answer my question.在提问之前,我想指出我确实看到了这个问题: Swift passing self as argument in class init ,但它并没有完全回答我的问题。 Or maybe I just want to see if these are the only solutions...或者也许我只是想看看这些是否是唯一的解决方案......

I have a couple of classes that's something like this.我有几个类是这样的。

class Bar {
    weak var delegate: FooDelegate?

    init(delegate: FooDelegate) {
        self.delegate = delegate
    }
}

class Foo: FooDelegate {
    var bar: Bar

    init() {
        self.bar = Bar(delegate: self)
    }
}

Before I updated, I don't remember this throwing any errors.在我更新之前,我不记得这会引发任何错误。 Now I'm getting the error Variable 'self.bar' used before being initialized .现在我收到错误Variable 'self.bar' used before being initialized

Is there a way to set this up so that I'm passing the delegate correctly?有没有办法设置它以便我正确地传递委托?

Thanks all!谢谢大家!

You can solve this by breaking it up in two steps, create the Bar object and then set delegate您可以通过分两步解决这个问题,创建Bar object 然后设置delegate

init() {
    bar = Bar()
    bar.delegate = self
}

Of course this requires a new init for the Bar class当然这需要一个新的init Bar class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在属性初始化程序中将self分配为委托 - Cannot assign self as delegate in property initializer 在实例变量 swift 的初始化程序中使用 self 作为委托 - Using self as delegate in initializer for instance variable swift 便利初始化程序必须委托自定义 UIView 初始化程序的 self.init 错误 - Convenience initializer must delegate with self.init error for custom UIView initializer 将不可用的初始化程序委托给可用的初始化程序 - Delegate a non-failable initializer to a failable initializer 具有 self.variable = variable 的初始化程序 - Initializer with self.variable = variable 为UICollectionViewFlowLayout提供我自己的初始化程序 - Providing my own initializer for UICollectionViewFlowLayout Swift:将Func作为参数传递给初始化器 - Swift: passing a func as a parameter in an initializer 在Swift UITableViewController初始化程序中传递数据 - Data passing in Swift UITableViewController Initializer 属性包装器:“不能在属性初始值设定项中使用实例成员;属性初始值设定项在 'self' 可用之前运行” - Property Wrappers: "Cannot use instance member within property initializer; property initializers run before 'self' is available" 不能在属性初始化器中使用实例成员''; 属性初始化程序在“自我”可用之前运行 - Cannot use instance member '' within property initializer; property initializers run before 'self' is available
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM