How to I customize the KVC and KVO methods in Swift?

Normally, you just declare properties in your `NSObject`-derived class as `@objc` and `dynamic`, and Swift automatically makes those properties KVC- and KVO-compliant. But that can't be done all the time. The class's "public properties" may be forwarding to some hidden object, and/or you may want to throw NSError upon a validation failure. (Swift will/did-set accessors cannot error out; you can only `fatalError` if the value is wrong). There are KVC and KVO Guides, that for a given key name we can use methods with special names to get/set/validate keyed values. Those guides are in Objective-C; I'm wondering what the equivalent method name patterns are for Swift.


(I want to dabble making a Mac app, planning to use KVC/O to connect the model to any actions affecting it. This means I need to way to transmit errors from trying to submit out-of-range values.)

Replies

The class's "public properties" may be forwarding to some hidden object, and/or you may want to throw NSError upon a validation failure. (Swift will/did-set accessors cannot error out; you can only `fatalError` if the value is wrong).

Can you show me some examples?


There are KVC and KVO Guides, that for a given key name we can use methods with special names to get/set/validate keyed values. Those guides are in Objective-C;

Can you show me the link to the guides and clarify what part are you referring.


(I want to dabble making a Mac app, planning to use KVC/O to connect the model to any actions affecting it. This means I need to way to transmit errors from trying to submit out-of-range values.)

As you write, Swift setters cannot throw errors. What do you expect transmit errors? What do you mean by trying to submit?


Explanation with codes (some of them may be pseudo or ideal) would help me understanding what you want to do.