swift - Swift 是否有任何内置的 Bool 反向函数?

标签 swift boolean

以下扩展有效,但我想知道 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/

相关文章:

c++ - 使用 Bool 函数确定 End

python - 根据另一个数据帧中的 boolean 值设置一个数据帧中的值

Java boolean 返回类型

java - 如何使用 JavaFX 将复选框的值传递给另一个方法?

objective-c - Objective C 和 Swift 是否支持分层继承?

ios 11 imessage 扩展 message.url 无法打开 safari

swift - UITextField rightView 图像和按钮?

python - Python中的字符串如何格式化 boolean 值?

ios - Manifest.plist 文件 ipad swift Playground

python - 将 JSON 数据发送到客户端 django