Object Oriented Programming

Properties in Swift

Properties are variables declared within classes or structures. There are three types: instance properties, static properties. There are also lazy properties, which are either instance or static properties, and are only initialized when used.

Equivalent to fields in other languages.


Syntax
modifier class className {
    // instance property
    modifier var variableName: dataType
    // static property, tied to class itself
    modifier static var variableName: dataType
    // lazy stored property, only initialized when used
    modifier lazy var variableName = value
}

Notes

Properties by default have getters and setters implicitly declared.

Properties can be declared with custom getters and setters.

Access modifiers are optional, all properties are declared internal by default..


Example
public class Car {
    var color: String
    static var numberOfWheels = 4; ///all cars have 4 wheels

    init(color: String) {
        self.color = color
    }
}

//access static property
print "Number of wheels: \(Car.numberOfWheels)"
//access instance property
var myCar = Car(color: "red")
print "My new car is \(myCar.color)"

< Type Methods   |   Getters and Setters >

© 2018 SyntaxDB. All Rights Reserved.