- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 89字
- 2021-07-02 14:44:58
Adding methods
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 = .on
state.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.