简体   繁体   English

如何在不更改属性值的情况下调用didSet

[英]How to call didSet without changing property value

I need the code in didSet to be executed without changing the property's value. 我需要在不改变属性值的情况下执行didSet的代码。

Coming from Objective-C recently, there doesn't seem to be a setMyProperty() . 最近来自Objective-C,似乎没有setMyProperty()

So I tried: 所以我尝试过:

self.myProperty = self.myProperty

which result in error Assigning a property to itself . 导致错误Assigning a property to itself

Because myProperty happens to be CGFloat , I could do: 因为myProperty恰好是CGFloat ,我可以这样做:

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. 它确实触发了didSet并且不会影响该值,但它没有显示我在这里的意思。

Is there a way to call didSet in a more clear/direct way? 有没有办法以更清晰/直接的方式调用didSet

试试这个:

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. myFunc myProperty时将调用myFunc You can also call myFunc directly, such as in the situation you required didSet to be called. 您也可以直接调用myFunc ,例如在您需要didSet的情况下。

didSet is called after the property value has already been changed. 在属性值已经更改之后调用didSet 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. 如果要将其还原为之前的值(因此具有与不更改属性值相同的效果),则需要为其指定“oldValue”属性。 Please take note that oldValue is not a variable defined by you, it comes predefined. 请注意, oldValue不是您定义的变量,它是预定义的。

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

You can use a tuple Swift 3 你可以使用一个元组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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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