简体   繁体   中英

Underlying Variable in a computed property | Swift

My problem is explained below. TLDR: my code requires me to use a third variable to represent the value of a computed property. I'm wondering if there is a way to do it with only two variables.

So I have a computed property called firstNumber which is a boolean. Everytime its value is changed, I want to change another variable, isDecimal , which is independent of firstNumber and has lots of different things that change it.

To do this, when firstNumber is set to false I also set isDecimal to false. The only issue is that I also need the firstNumber boolean to have a value, so I created an underlying boolean called firstNumberAPI .

I don't think this is the best way to do what I'm trying to do. I am wondering if someone can suggest a way to set isDecimal when firstNumber is changed, without creating a third, firstNumberAPI variable.

var isDecimal = false
var firstNumberAPI = false

var firstNumber: Bool{
    get{
        return firstNumberAPI
    }
    set{
        firstNumberAPI = newValue
        if newValue==true{
            isDecimal = false
        }
        else{
            isDecimal = true
        }
    }
}

There's no need for the firstNumberAPI variable. Change firstNumber to:

var isDecimal = false

var firstNumber: Bool {
    didSet {
        isDecimal = !firstNumber
    }
}

See the Property Observers section of the The Swift Programming Language book for details on didSet .

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