O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required