The structure

Apple has not only said that Swift developers should prefer value types over reference types, but they have also been taking that philosophy to heart. If we look at the Swift standard library (https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html), we will see that the majority of the types are implemented using structures. The reason Apple is able to implement the majority of Swift's standard library with structures is that, in Swift, structures have many of the same functionalities as classes. There are, however, some fundamental differences between classes and structures and we will be looking at these differences later in this chapter.

In Swift, a structure is a construct that allows us to encapsulate the properties, methods, and initializers of an instance into a single type. They can also include other items, such as subscripts. However, we are going to focus on the basic items that make up a structure. This description may sound a lot like how we described classes in the last section. This is because classes and structures are so similar in Swift.

Let's see how we could create a structure. The following example shows how we could create a Drink structure that has the same functionality as the Drink class:

struct Drink {
    var volume: Double
    var caffeine: Double
    var temperature: Double
    var drinkSize: DrinkSize
    var description: String
    
    mutating func drinking(amount: Double) {
        volume -= amount
    }
    mutating func temperatureChange(change: Double) {
        temperature += change
    }
}

If we compare this Drink structure to the Drink class from the previous section, we can see some very basic differences. In the Drink structure, we are not required to define an initializer because the structure will create a default initializer for us if we do not provide one. This default initializer will require us to provide initial values for all the properties of the structure when we create an instance of it.

The other difference between the structure and the class is the mutating keyword used for each function in the structure. Structures are value types; therefore, by default, the properties of the structure cannot be changed from within the instance methods. By using the mutating keyword, we are opting for the mutating behavior of that particular method. We must use the mutating keyword for any method within the structure that changes the values of the structure's properties.

We could create an instance of the Drink structure as follows:

var myDrink = Drink(volume: 23.5, caffeine: 280,
    temperature: 38.2, drinkSize: DrinkSize.Can24,
    description: "Drink Structure")

The structure is a named type because, when we create instances of the type, it is named. The structure type is also a value type.

The next type that we are going to look at is Swift's supercharged enumerations.