Swift:Closure作为类变量中的init参数

时间:2015-11-17 12:52:36

标签: swift closures init

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

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

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

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

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'

我读过的所有内容都告诉我,我已经做到了这一点,但是我没有看到任何使用类的实例设置var的示例,该类将闭包作为init参数。

有没有人这样做或知道下一步该尝试什么?或者有更好的方法吗?

作为旁注,此代码的目标是有效地为Calculator类提供一种方法,以便在值发生更改时通知AnotherClass。我环顾四周,但我不确定哪种技术最适合这样做。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

通过在操场上摆弄,我可以近距离接触到你想要的东西。我必须更改类型以匹配您传递给计算器

的内容
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时似乎存在问题(即使看起来你应该能够因为你指定了懒惰和弱或无主等)