1

I did bind a textfield to a Swift dictionary value via interface builder. In the textfield the correct value is pulled from the dictionary and displayed in the textfield.

When I change the value of the element in the dict via

myDict["Textfield1"] = "New value"

the change is not visible in the textfield. When I do bind the value of the textfield to a property of a class, any change to this property is instantly visible in the textfield. Am I missing something?

Thanks!

Mike Nathas
  • 1,247
  • 2
  • 11
  • 29

1 Answers1

1

So basically, it won't work. Bindings work by using the KVO/KVN system, which sends out notifications when Obj-C objects change their value. It's very clever, but they didn't port it to Swift. To add to that, dictionaries in Swift are value types.

The "solution" is to make sure the thing you bind to has KVO. So there's a couple of things you can do. The first is to make your own class and subclass it from NSObject, and presto, you get KVO. Here's a page on how to do that.

But the better way is to use the dynamic keyword on your Swift collection, myDict. This triggers the bridging into Obj-C, and so you get KVO. Now I haven't used this with a Swift dict, so I'm not totally sure what will happen. You may have to make the myDict a NSDictionary. But it's one minor change, so definitely give dynamic a try!

Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98
  • Using dynamic ans subclassing from NSObject did the trick. After a few months with Swift it seems that there is very much stuff to do for apple until objc support can be dropped :) Thanks for your help! – Mike Nathas Sep 21 '16 at 19:32
  • My pleasure. And when it's time to get fancy, use https://github.com/ReactiveKit/ReactiveKit – Maury Markowitz Sep 21 '16 at 19:40