Does Swift have any built-in reverse function for a Bool?
Swift 4.2 and above.
As pointed out by Martin previously, the toggle function has finally arrived
So now, you can simply write
bool.toggle()
and that would give you the intended results.
!
is the "logical not" operator:
var x = true
x = !x
print(x) // false
In Swift 3 this operator is defined as a static function of the Bool
type:
public struct Bool {
// ...
/// Performs a logical NOT operation on a Boolean value.
///
/// The logical NOT operator (`!`) inverts a Boolean value. If the value is
/// `true`, the result of the operation is `false`; if the value is `false`,
/// the result is `true`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// - Parameter a: The Boolean value to negate.
prefix public static func !(a: Bool) -> Bool
// ...
}
There is no built-in mutating method which negates a boolean,
but you can implement it using the !
operator:
extension Bool {
mutating func negate() {
self = !self
}
}
var x = true
x.negate()
print(x) // false
Note that in Swift, mutating methods usually do not return the new
value (compare sort()
vs. sorted()
for arrays).
Update: The proprosal
- SE-0199 Adding
toggle
toBool
has been accepted, and a future version of Swift will have a
toggle()
method in the standard library:
extension Bool {
/// Equivalent to `someBool = !someBool`
///
/// Useful when operating on long chains:
///
/// myVar.prop1.prop2.enabled.toggle()
mutating func toggle() {
self = !self
}
}
For above swift 4.2
var isVisible = true
print(isVisible.toggle()) // false
for else
isVisible = !isVisible