Toggling Booleans
Published on Dec 10, 2019Toggling Booleans β SwiftMoji Entry #12
One very common task in programming is to switch the value of a boolean. This is generally accomplished using the prefix operator ! like so a = !a. However, when changing the value of a boolean nested within multiple structs or classes, this can often become unwieldy. Thankfully, Swift provides an elegant solution to this problem. The Bool struct contains a mutating method called toggle(), that when called, switches the value in-place. Additionally, the method is marked with the @inlinable attribute. This allows the Swift compiler to replace calls to toggle with the implementation (self = !self) wherever itβs used. This ensures that users of the toggle method experience no overhead due to entering and exiting scopes.
struct House {
var address: String
var isπ‘On: Bool = false
}
var π = House(address: "P. Sherman 42 Wallaby Way, Sydney")
π .isπ‘On = !π .isπ‘On // π«
π .isπ‘On.toggle() // β
Tagged with: