Swift:闭包作为 class 变量中的初始参数

Swift: Closure as a init argument in a class variable

我有一些代码看起来像这样:

class Calculator {
    private let estimateChanged:(newEstimate:Double) -> Void

    init(_ estimateChanged:(newEstimate:Double) -> Void) {
        self.estimateChanged = estimateChanged
    }
}

另一个class正在使用它。目前我正在尝试设置一个包含计算器的 属性:

class AnotherClass {
    private lazy var calculator = Calculator({ [unowned self] in
        self.loadEstimate()
    })
    func loadEstimate() {}
}

我遇到了错误。首先它说 [unowned self] 给我错误:'unowned' cannot be applied to non-class type 'AnotherClass -> () -> AnotherClass'

其次 self.loadEstimate() 我得到:value of type 'AnotherClass -> () -> AnotherClass' has no member 'loadEstimate'

我读过的所有内容都向我表明我做对了,但是我没有看到任何使用 class 实例设置 var 的示例,该实例将闭包作为 init参数。

有没有人这样做过或知道接下来要尝试什么?或者有更好的方法吗?

附带说明一下,此代码的目标是有效地为计算器 class 提供一种在值更改时通知 AnotherClass 的方法。我环顾四周,但不确定哪种技术最适合执行此操作。有什么建议吗?

这是我在操场上摆弄的最接近你想要的东西。我必须更改类型以匹配您传递给计算器的内容

class Calculator {
    private let estimateChanged:() -> Void

    init(_ estimateChanged:() -> Void) {
        self.estimateChanged = estimateChanged
    }
}

class AnotherClass {
    lazy var callback: () -> Void = { [unowned self] in
        self.loadEstimate()
    }
    var calculator: Calculator?

    // viewDidLoad in the case of a view controller
    init() {
        calculator = Calculator(callback)
    }

    func loadEstimate() {}
}

这显然不是您想要的,但可以编译。尝试在未初始化的对象中引用 self 时似乎存在问题(即使您似乎应该能够这样做,因为您指定了 lazy 和 weak 或 unowned 等)