11

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?

meaning-matters
  • 21,929
  • 10
  • 82
  • 142
  • 4
    In my opinion `didSet` as it name indicates, means that the property has been set to a value, so trying to execute didSet without changing the value doesn't make sense and it makes your code unclear. – Swifty Oct 05 '16 at 07:39

4 Answers4

29

Try this:

self.myProperty = { self.myProperty }()
Orkhan Alikhanov
  • 9,122
  • 3
  • 39
  • 60
2

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.

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • I thought about this, but continued looking for a 'native' Swift construction. My `didSet` is just two lines so I didn't want to just add a function for that. – meaning-matters Oct 05 '16 at 07:28
0

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
    }
}
andrei
  • 1,353
  • 15
  • 24
0

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
Rob
  • 2,649
  • 3
  • 27
  • 34
  • It's technically interesting. It would require a change to all the code that uses this property; not a good thing. I'll up two of your other answers (giving you 20 points) as thanks for the effort and idea. – meaning-matters Oct 05 '16 at 11:35