Boolean toggling
About 2 min
Boolean toggling 관련
HACKING WITH SWIFT
What's new in Swift?
Boolean toggling | Changes in Swift 4.2
Boolean toggling
Available from Swift 4.2
SE-0199 (apple/swift-evolution
) introduced a new toggle()
method to booleans that flip them between true and false..
The entire code to implement proposal is only a handful of lines of Swift:
extension Bool {
mutating func toggle() {
self = !self
}
}
However, the end result makes for much more natural Swift code:
var loggedIn = false
loggedIn.toggle()
As noted in the proposal, this is particularly useful in more complex data structures: myVar.prop1.prop2.enabled.toggle()
avoids the potential typing errors that could be caused using manual negation.
The proposal makes Swift easier and safer to write, and is purely additive, so I think most folks will switch to using it quickly enough.
Other Changes in Swift 4.2
Derived collections of enum cases | Changes in Swift 4.2
Derived collections of enum cases
Warning and error diagnostic directives | Changes in Swift 4.2
Warning and error diagnostic directives
Dynamic member look up | Changes in Swift 4.2
Dynamic member look up
Enhanced conditional conformances | Changes in Swift 4.2
Enhanced conditional conformances
Random number generation and shuffling | Changes in Swift 4.2
Random number generation and shuffling
Simpler, more secure hashing | Changes in Swift 4.2
Simpler, more secure hashing
Checking sequence elements match a condition | Changes in Swift 4.2
Checking sequence elements match a condition
In-place collection element removal | Changes in Swift 4.2
In-place collection element removal