Mutating Methods

Recall from Chapter 14 and Chapter 15 that methods on value types (structs and enums) cannot modify self unless the method is marked as mutating. Methods in protocols default to nonmutating. In the Lightbulb enum from Chapter 14, the toggle() method was mutating.

enum Lightbulb {
    case On
    case Off

    mutating func toggle() {
        switch self {
        case .On:
            self = .Off

        case .Off:
            self = .On
        }
    }
}

Suppose you want to define in a protocol that an instance is “toggleable”:

protocol Toggleable {
    func toggle()
}

Declaring that Lightbulb conforms to Toggleable would result in a compiler error. The message you get includes a note that explains the problem:

error: type 'Lightbulb' does not conform to protocol 'Toggleable' note: ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.