I want to keep two properties in sync with Cocoa bindings.
In my code, you can see that I have two classes: A
and B
. I wish to keep the message
values in A
and B
instances synchronized so that a change in one is reflected in the other. I'm trying to use the bind(_:to:withKeyPath:options:)
method of the NSKeyValueBindingCreation
informal protocol. I use Swift 4.2 on macOS.
import Cocoa
class A: NSObject {
@objc dynamic var message = ""
}
class B: NSObject {
@objc dynamic var message = ""
init(_ a: A) {
super.init()
self.bind(#keyPath(message), to: a, withKeyPath: \.message, options: nil) // compile error
}
}
I get a compile error in the line where I call bind: cannot convert value of type 'String' to expected argument type 'NSBindingName'
. I get the suggestion to wrap the first parameter with NSBindingName(rawValue: )
. After applying that, I get the error type of expression is ambiguous without more context
for the third parameter.
What am I doing wrong?