简体   繁体   中英

How to call didSet without changing property value

I need the code in didSet to be executed without changing the property's value.

Coming from Objective-C recently, there doesn't seem to be a setMyProperty() .

So I tried:

self.myProperty = self.myProperty

which result in error Assigning a property to itself .

Because myProperty happens to be CGFloat , I could do:

self.myProperty += 0.0

which does trigger didSet and does not affect the value, but it doesn't show what I mean to do here.

Is there a way to call didSet in a more clear/direct way?

试试这个:

self.myProperty = { self.myProperty }()

You could do:

struct MyStruct {
    var myProperty: CGFloat {
        didSet {
            myFunc()
        }
    }

    func myFunc() { ... }
}

Here myFunc will be called when myProperty is set. You can also call myFunc directly, such as in the situation you required didSet to be called.

didSet is called after the property value has already been changed. If you want to revert it to it's previous value(so having the same effect as not changing the property's value), you need to assign it 'oldValue' property. Please take note that oldValue is not a variable defined by you, it comes predefined.

var myProperty: CGFloat {
    didSet {
        myProperty = oldValue
    }
}

You can use a tuple Swift 3

var myProperty : (CGFloat,Bool) = (0.0, false){

            didSet {
                if myProperty.1 {

               myProperty = (0.0, false) // or (oldValue.0, false)

                    //code.....
                }else{

                    // code.....
                }
            }


        }

    myProperty = (1.0, true)

    print(myProperty.0) //print 0.0

    myProperty = (1.0, false)

    print(myProperty.0) //print 1.0

    myProperty = (11.0, true)

    print(myProperty.0) //print 0.0

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