Object Oriented Programming

Getters and Setters in Swift

In Swift, like other languages, getters and setters don't need to be declared for public variables.

The getter and setter implementation can be overwritten in Swift for all types of variables, including private.


Syntax
//within a class or structure

var variableName: dataType {
    get {
        //code to execute
        return someValue
    }
    set(newValue) {
        //code to execute
    }
}

Notes

Usually used to set getter and setter behavior for classes within classes, and private variables.


Example
struct Processor {
    var mhz: Double
    init(mhz: Double) {
        self.mhz = mhz
    }
    var ghz: Double {
        get {
            return mhz * 0.001
        }
        set(newGhz) {
            self.ghz = newGhz
            self.mhz = newGhz * 1000
        }
    }
}

< Properties   |   Inheritance >

© 2019 SyntaxDB. All Rights Reserved.