Object Oriented Programming

Structures in Swift

Structures are classes which are value-typed, similar to previous variables and lets.

Structures, like classes, contain methods and properties.


Syntax
struct structureName {
    //properties and methods declared here
}

//instantiating a structure, with properties (also called fields)
var structureInstance = structureName(fieldName: fieldValue)

//accessing structure public method or field
var structureInstance.structureMember

Notes

Structures cannot be inherited, deinitialized or type cast.

Because structures are value typed, when they are passed around in code, a new copy is always made of the instance.

As a guideline, structures are used when encapsulating other value types.


Example
//structure declaration
struct Circle {
    var radius: Double = 0;

    func area() -> Double {
        return radius * radius * 3.14
    }

    func circumference() -> Double {
        return radius * 2 * 3.14
    }
}

//structure instance
var wheel = Circle(5.3)
print "The area of the wheel is \(wheel.area())"

< Map   |   Class Declaration >

© 2019 SyntaxDB. All Rights Reserved.