2017-09-16 3 views
0

私はReactiveSwiftとReactiveCocoaを使ってかなり新しく、依存関係を持つPropertyを初期化する適切な方法についてロードブロックを打ったようです。複数の依存関係を持つ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

Sweet!この詳細な説明をありがとうございます! :) –

関連する問題