For the More Curious: Mutating Methods

After working through this chapter, you might be wondering about the mutating keyword. Why is it needed to allow you to modify a struct or enum? A useful place to start is to revisit functions that return functions.

Create a new playground called Mutating. Add a simple function to your playground that returns a String greeting.

Listing 15.16 A simple greeting function

func greet(name: String, withGreeting greeting: String) -> String {
    return "\(greeting) \(name)"
}

The greet(name:withGreeting:) function takes two arguments: a name and a greeting. It constructs and returns a greeting based on these two arguments. This function is straightforward to use.

Listing 15.17 Using greet(name:withGreeting:) ...

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.