Swift Language Basics of Structs

Download Swift Language for free

Example

struct Repository {
    let identifier: Int
    let name: String
    var description: String?
}

This defines a Repository struct with three stored properties, an integer identifier, a string name, and an optional string description. The identifier and name are constants, as they've been declared using the let-keyword. Once set during initialization, they cannot be modified. The description is a variable. Modifying it updates the value of the structure.

Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. The structure receives a memberwise initializer even if it has stored properties that do not have default values.

Repository contains three stored properties of which only description has a default value (nil). Further it defines no initializers of its own, so it receives a memberwise initializer for free:

let newRepository = Repository(identifier: 0, name: "New Repository", description: "Brand New Repository")
Mutating a Struct