初始化具有多个依赖性的RAC ReactivesWift属性



我使用reactiveswift和reactivecocoa是相当新的,我似乎已经对具有依赖性的属性的适当方式碰到了路障。

例如,在以下代码中,我尝试初始化一个属性,但我会收到一个预期的编译器错误。我的问题是如何/什么是"正确"的方法。

class SomeViewModel {
// illustration purposes, in reality the property (dependency) we will observe will change over time
let dependency = Property(value: true)
let dependency2 = Property(value: "dependency2")
let dependency3 = Property(value: 12345)
let weightLabel: Property<String>
// private(set) var weightLabel: Property<String>!
// using private(set) var weightLabel: Property<String>! works, 
// however this changes the meaning behind using let, because we could
// reinitalize weightLabel again which is not similar to using a let so not a good alternative
// let weightLabel: Property<String> = Property(value: "")
// another solution that will work but will result in a wrong value
// upon initalization then, changed into the "correct value" thus, i
// am discrading this as well
init() {
    weightLabel = dependency.map {
        // compiler error, 'self' captured by closure before all members were initalized. 
        // My question is if there is a way to handle this scenario properly
        if $0 && self.dependency2.value == "dependency2" && self.dependency3.value == 12345 {
            return ""
        }
        return ""
    }
}
}

因此,正如您在评论中可能已经注意到的那样,我想知道是否有一种方法可以使用ReactiveSwift来处理这种情况,而其他我提到的情况并不是真正理想的解决方案。

适合该方案的仪器是combineLatest,只要有任何一个更新,它提供了所有这些属性(流)的组合版本。

weightLabel = Property.combineLatest(dependency, dependency2, dependency3)
    .map { d1, d2, d3 in
        return "Hello World! (d1) (d2) (d3)"
    }

关于编译器错误,问题在于,您要在闭合中捕获/引用 self,然后在每个存储的属性都开始初始化之前。根据意图,您可以使用A 捕获列表直接捕获带有 self的值和对象。

let title: String
let action: () -> Void
init() {
    title = "Hello World!"
    // 🚫 `action` has not been initialised when `self` is
    // being captured.
    action = { print(self.title) } 
    // ✅ Capture `title` directly. Now the compiler is happy.
    action = { [title] in print(title) }
}

相关内容

  • 没有找到相关文章

最新更新