How to use Cocoa bindings to Swift strings

I am learning Swift.

Mostly I work in iOS, but now I am working on a small project for OS X.

On OSX, I like to use Cocoa bindings to bind values ​​from my model to user interface elements. This saves writing tons of glue code.

I am writing a program that compares Swift performance with C / Objective-C performance. I am using a prime generator as a test project.

I created Swift Struct ComputeSettings , which encapsulates the settings (and results) to run the prime generator in both Swift and Objective-C. The structure is as follows:

 struct ComputeResults { var totalCalculated: Int = 0 var primesPerSecond: Int = 0 var totalTime: NSTimeInterval = 0 } struct ComputeSettings { var totalToCalculate: Int = 10000000 var swiftResults: ComputeResults = ComputeResults() var objCResults: ComputeResults = ComputeResults() } 

Then I have an instance variable of type ComputeSettings in my view controller:

 class ViewController: NSViewController { var theComputeSettings = ComputeSettings() var foo: Int = 12 //... } 

In my user interface, I have a text box that allows the user to enter the number of primes to calculate. In IB, I select a field, select the bindings tab in the utilities area, and then open the value bindings. I am attached to the ViewController class. I entered the key path of the self.theComputeSettings.totalToCalculate model.

When I run the project, it crashes out:

Failed to set (contentViewController) user-defined validation property on (NSWindow): [addObserver: forKeyPath: @ "theComputeSettings.totalToCalculate": 256 context: 0x0] was sent to an object that does not match the KVC for "TheComputeSettings" property.

If instead I snap to the dummy foo property (so the model key path is set to self.foo ), it works fine. In this case, I see that my text box displays my value of 12.

Is there a way to use Swift structures and still use Cocoa bindings? I have done quite a lot of googling but can't find anything.

Of course, I can do it manually, and write a bunch of glue code to set my values ​​from my structure to my windows, but I would rather use Cocoa bindings. What are they needed for.

+7
struct swift cocoa-bindings macos
source share
1 answer

You cannot use Cocoa bindings with Swift strings.

Cocoa's binding system is implemented on top of the Key-Value Observing, and key value monitoring is implemented by creating a subclass to intercept the set<Property>: messages sent to the observed object. Swift structures cannot be subclassed and it is not necessary to use messages or function calls to set structure fields, so it is generally not possible to intercept the field setting of a Swift structure.

The message complains about the lack of KVC compliance, because Key-Value Coding defines the set<Property>: (and <property> getter) convention for message names.

+9
source share

All Articles