The nice thing about Swift’s value types is that you can decide whether they are immutable or mutable at the point you use them. For example, consider the
String
type. You can declare a string variable in two ways:
let immutableString: String = "immutable string"
var mutableString: String = "mutable"
mutableString.appendContentsOf(" string")
This approach is nice for a variety of reasons. Let me know if you want me to go into that aspect of things.
For this to work the compiler has to know which methods of the type can change the state of the type. You declare that via the
mutating
keyword. The keyword has two effects:
In short, the
mutating
keyword is what allows the compiler to enforce these requirements.
To expand on the first requirement, both of the following statements work because
hasSuffix(_:)
is a normal method:
print(immutableString.hasSuffix(" string"))
print(mutableString.hasSuffix(" string"))
but the first of this next pair fails because
appendContentsOf(_:)
is a mutating method:
immutableString.appendContentsOf(" string") // this fails
mutableString.appendContentsOf(" string")
To expand on the second requirement, adding a string extension like this:
extension String {
mutating func borkString() {
self = self + " bork bork bork"
}
}
requires that you use the
mutating
keyword because the code changes the value itself. If you leave off the keyword, you get an error.
OTOH, this extension, which doesn’t mutate the value, doesn’t need the
mutating
keyword:
extension String {
func borkedString() -> String {
return self + " bork bork bork"
}
}
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"