First of all, note that the discussion keyword is , not . mutating
mutable
The default state set
ismutating
- To quickly answer your question:
mutating
- this is the default state for setters, and therefore you do not need to explicitly use the keyword mutating
to indicate this.
More details
The following default behavior is performed for getter and seters:
get
nonmutating
defaultset
mutating
default
, , ... { get set }
, ( ), , nonmutating get
mutating set
struct
,
protocol Deck {
var cards: [String] {get set}
}
// implicitly, OK
struct MyDeckA: Deck {
var mutateMe: Int = 0
var cards: [String] {
get { return ["foo"] }
set { mutateMe += 1 }
}
}
struct MyDeckB: Deck {
var mutateMe: Int = 0
var cards: [String] {
nonmutating get { return ["foo"] }
mutating set { mutateMe += 1 }
}
}
struct MyDeckC: Deck {
var mutateMe: Int = 0
var cards: [String] {
mutating get { return ["foo"] }
mutating set { mutateMe += 1 }
}
}
, , ( , , ).
protocol Deck {
var cards: [String] {mutating get nonmutating set}
}
/* when conforming to this non-default get/set setup blueprinted in
protocol Deck, we need to explicitly specify our non-default
(w.r.t. mutating) getter and setter */
struct MyDeckD: Deck {
var mutateMe: Int = 0
var cards: [String] {
mutating get { mutateMe += 1; return ["foo"] }
nonmutating set { print("I can't mutate self ...") }
}
}
, , ( ) (... {get set}
), , , mutating set
, nonmutating
protocol Deck {
var cards: [String] {get set}
}
struct MyDeckE: Deck {
var mutateMe: Int = 0
var cards: [String] {
get { return ["foo"] }
nonmutating set { print("I can't mutate self ...") }
}
}
, , , , , , , , self
. , , get mutating
getter: - nonmutating
one.
protocol Deck {
var cards: [String] {mutating get set}
}
struct MyDeckF: Deck {
var mutateMe: Int = 0
var cards: [String] {
nonmutating get { print("I can't mutate self ..."); return ["foo"] }
set { mutateMe += 1 }
}
}