December 2018
Intermediate to advanced
414 pages
10h 19m
English
Now, we may want to add a method to this State enumeration. After all, it's very common to just toggle the switch on and off without thinking:
extension State { mutating func toggle() { self = self == .off ? .on : .off }}var state: State = .onstate.toggle()state == .off // true
As in the previous section, we can just extend the State enum to add the toggle functionality. Enums follow value semantics; therefore, we have to mark the toggle method as mutating.
Read now
Unlock full access