Mike Nathas Mike Nathas - 2 months ago 11
Swift Question

Xcode - Bind textfield to element of a Swift dictionary

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!

Answer

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!

Comments