简体   繁体   中英

Swift willSet/didSet assignment?

I want to observe changes on couple of properties in my class by using the didSet / willSet API. However I'd like to keep my properties decelaration section clean, so I want to have separate functions for implementations of this logic.

Right now I have something like this:

var myProperty: SomeType {
    didSet {
        handleDidSetMyProperty()
    }
}

However this takes up 5 lines, which is quite a lot if you have more of such properties. It would be great if I could limit this to 3, for example like this:

var myProperty: SomeType {
    didSet = handleDidSetMyProperty
}

Is there a way in Swift to assign a function/closure to a property observer?

No, you can't. See Declarations in the Swift Programming Language.

In “GRAMMAR OF A VARIABLE DECLARATION” you'll find

didSet-clause → attributes­opt ­didSet­ setter-name­­opt ­­code-block­

and in “GRAMMAR OF A CODE BLOCK”

code-block → {­ statements­opt

ie the didSet keyword can only be followed by a code block (with mandatory curly braces).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM