以下扩展工作,但我想知道Swift是否有任何开箱即用的功能,这样做反向.我已经命令点击Bool,它没有任何反转,也没有在文档中看到任何内容.
var x = true
extension Bool{
mutating func reverse() -> Bool{
if self == true {
self = false
return self
} else {
self = true
return self
}
}
}
print(x.reverse()) // false
Run Code Online (Sandbox Code Playgroud)
Mar*_*n R 24
!
是"逻辑非"运算符:
var x = true
x = !x
print(x) // false
Run Code Online (Sandbox Code Playgroud)
在Swift 3中,此运算符被定义为Bool
类型的静态函数:
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
// ...
}
Run Code Online (Sandbox Code Playgroud)
没有内置的变异方法否定布尔值,但您可以使用!
运算符实现它:
extension Bool {
mutating func negate() {
self = !self
}
}
var x = true
x.negate()
print(x) // false
Run Code Online (Sandbox Code Playgroud)
请注意,在Swift中,变异方法通常不会返回新值(sort()
与sorted()
数组进行比较).
更新: proprosal
已被接受,未来版本的Swift将toggle()
在标准库中有一个
方法:
extension Bool {
/// Equivalent to `someBool = !someBool`
///
/// Useful when operating on long chains:
///
/// myVar.prop1.prop2.enabled.toggle()
mutating func toggle() {
self = !self
}
}
Run Code Online (Sandbox Code Playgroud)
Meh*_*mar 14
正如Martin先前所指出的那样,切换功能终于到来了
所以现在,你可以简单地写
bool.toggle()
Run Code Online (Sandbox Code Playgroud)
这会给你预期的结果.
对于 swift 4.2 以上
var isVisible = true
print(isVisible.toggle()) // false
Run Code Online (Sandbox Code Playgroud)
为别的
isVisible = !isVisible
Run Code Online (Sandbox Code Playgroud)