Execute a method when a variable value changes in Swift

后端 未结 5 1580
时光说笑
时光说笑 2020-12-25 10:47

I need to execute a function when a variable value changes.

I have a singleton class containing a shared variable called labelChange. Values of this va

5条回答
  •  無奈伤痛
    2020-12-25 11:47

    Apple provide these property declaration type :-

    1. Computed Properties:-

    In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

    var otherBool:Bool = false
    public var enable:Bool {
        get{
            print("i can do editional work when setter set value  ")
            return self.enable
        }
        set(newValue){
            print("i can do editional work when setter set value  ")
            self.otherBool = newValue
        }
    }
    

    2. Read-Only Computed Properties:-

    A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

    var volume: Double {
        return volume
    }
    

    3. Property Observers:-

    You have the option to define either or both of these observers on a property:

    willSet is called just before the value is stored.
    didSet is called immediately after the new value is stored.

    public  var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
    

    NOTE:- For More Information go on professional link https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

提交回复
热议问题