以下扩展有效,但我想知道 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
最佳答案
!
是“逻辑非”运算符:
var x = true
x = !x
print(x) // false
在 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
// ...
}
没有内置的改变 boolean 值的方法,
但您可以使用 !
运算符实现它:
extension Bool {
mutating func negate() {
self = !self
}
}
var x = true
x.negate()
print(x) // false
请注意,在 Swift 中,变异方法通常不会返回新的
值(比较数组的 sort()
与 sorted()
)。
更新:提案
已被接受,Swift 的 future 版本将有一个
toggle()
标准库中的方法:
extension Bool {
/// Equivalent to `someBool = !someBool`
///
/// Useful when operating on long chains:
///
/// myVar.prop1.prop2.enabled.toggle()
mutating func toggle() {
self = !self
}
}
关于swift - Swift 是否有任何内置的 Bool 反向函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399225/