Does Swift have a built-in flyback function for Bool?

The following extension works, but I was wondering if Swift has any function from the window that does the opposite. I already commanded a click on Bool, and it has nothing to do with it, just like I did not see anything in the documentation.

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
+4
source share
3 answers

! - this is the logical not operator:

var x = true
x = !x
print(x) // false

In Swift 3, this operator is defined as a static function Bool Type:

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

   // ...
}

There is no built-in mutation method that overrides the boolean, but you can implement it using the operator !:

extension Bool {
    mutating func negate() {
        self = !self
    }
}

var x = true
x.negate()
print(x) // false

, Swift ( sort() vs. sorted() ).


:

Swift toggle() :

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

, x = false;

, , x = !x;. ( true false false true.)

( , C x ^= 1, .)

+1

- bool false, :

 var mybool = true
 mybool = mybool == false

mybool oposite ,

0

Source: https://habr.com/ru/post/1665349/


All Articles