2

I am using ReactiveSwift to create a struct containing a dictionary. I want to listen for changes in the dictionary.

struct Model {
    let a: MutableProperty<[String: Int]> = MutableProperty([:])
}

However, I'm having a hard time understanding how to bind this property to a listener. I want to do something like:

textView.reactive.text <~ model.a["key"]

Is there a solution to holding dictionaries in mutable properties?

sdasdadas
  • 23,917
  • 20
  • 63
  • 148

2 Answers2

3

Only the MutableProperty associated value (in your case, the dictionary) is able to be binded to the binding target, and not a value within the dictionary. That means you can't use the <~ operator on a value from the dictionary. You'll need to do something like:

model.a.producer.startWithValues { [weak textView] value in
     textView?.text = value["key"]
}
tkuichooseyou
  • 650
  • 1
  • 6
  • 16
  • Thanks, this is very useful! I ended up making the properties inside my dictionary mutable, but that assumes the dictionary is a fixed size. Your answer works for the unknown case. – sdasdadas Mar 01 '17 at 09:01
1

Or you can do it like this:

textView.reactive.text <~ model.a.map { $0["key"] }
biobod
  • 11
  • 2