Overload the '!' Logical NOT Operator for Custom Swift Types
Written by Team Kodeco
The !
operator in Swift is used for performing a logical NOT operation, which reverses the truth value of a Boolean. When working with custom types in Swift, you may want to overload the !
operator to perform a similar operation specific to your custom type.
To overload the !
operator in Swift, you’ll need to define a function called !
with no parameters and the operator keyword before the function name. Here’s an example of how you might overload the !
operator for a custom LightSwitch class:
class LightSwitch {
var on: Bool
init(on: Bool) {
self.on = on
}
static prefix func ! (lightSwitch: LightSwitch) -> LightSwitch {
return LightSwitch(on: !lightSwitch.on)
}
}
In this example, you define a LightSwitch
class with an on property indicating whether the switch is on or off. You then define an operator function as a prefix function that takes a LightSwitch
as parameter and returns a new LightSwitch
instance with the opposite value of the on property.
Now you can use the !
operator to toggle the on/off state of a LightSwitch
instance:
var lightSwitch = LightSwitch(on: true)
print(lightSwitch.on) // true
lightSwitch = !lightSwitch
print(lightSwitch.on) // false