2017-09-16 87 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

甜!感謝您的詳細解釋! :) –

相關問題