Grant Emerson

Toggling Booleans

Toggling 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: