2017-09-16 54 views
0

我对于使用ReactiveSwift和ReactiveCocoa相当新颖,而且我似乎碰到了关于初始化具有依赖关系的属性的正确方法的障碍。初始化具有多个依赖关系的RAC ReactiveSwift属性?

例如在下面的代码,我尝试初始化属性,但我得到预计编译错误。我的问题是如何/什么是“正确”的方式来做到这一点。

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其他然后我上面提到的那些不甚理想的解决方案的人的一种方式。

回答

3

适合场景的仪器是combineLatest,其中规定,只要其中的任何已更新所有这些属性(流)的组合版本。

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

关于编译器错误,问题是,你捕获/指self在封闭每个存储的属性已经被初始化之前。根据意图,您可以使用捕获列表直接捕获您感兴趣的值和对象,而不是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) } 
} 
+0

甜!感谢您的详细解释! :) –

相关问题