Swift是否具有BOOL的任何内置反向功能



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

没有内置的突变方法来否定布尔值,但是您可以使用!操作员实现它:

extension Bool {
    mutating func negate() {
        self = !self
    }
}
var x = true
x.negate()
print(x) // false

请注意,在迅速,突变方法通常不会返回新的值(比较sort()sorted()的数组)。


更新: Proprosal

  • SE-0199将toggle添加到Bool

已被接受,未来版本的Swift将有一个 标准库中的toggle()方法:

extension Bool {
  /// Equivalent to `someBool = !someBool`
  ///
  /// Useful when operating on long chains:
  ///
  ///    myVar.prop1.prop2.enabled.toggle()
  mutating func toggle() {
    self = !self
  }
}

swift 4.2及以上。

正如马丁先前指出的那样,切换功能终于到达

现在,您可以简单地写

bool.toggle()

这将为您带来预期的结果。

对于上述Swift 4.2

var isVisible = true
print(isVisible.toggle())  // false

else

isVisible = !isVisible

做到这一点的最佳方法和最简单的方法之一就是检查当您这样设置时,布尔等于错误:

 var mybool = true
 mybool = mybool == false

MyBool将始终是

之前它的原样

在进行编辑之前,您的功能等同于琐碎的分配x = false;

但是,您现在可以将其简化为x = !x;。(即 true映射到falsefalse映射到true。)

(请注意,C中的酷猫甚至可能使用x ^= 1,TO toggle 最不重要的位。)

最新更新