How to Get the Opposite Value of a Bool in Swift

How can I get the opposite value of a Bool in Swift?

The exclamation point is on the wrong side of the boolean. The way you've written it would indicate that the boolean could be nil. You want !navHidden.

Does Swift have any built-in reverse function for a Bool?

! is the "logical not" operator:

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

In Swift 3 this operator is defined as a static function of the 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 mutating method which negates a boolean,
but you can implement it using the ! operator:

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

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

Note that in Swift, mutating methods usually do not return the new
value (compare sort() vs. sorted() for arrays).


Update: The proprosal

  • SE-0199 Adding toggle to Bool

has been accepted, and a future version of Swift will have a
toggle() method in the standard library:

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

SwiftUI - Invert a boolean binding

You can build a binding by yourself:

Text("Here is a cool Text!").sheet(isPresented:
Binding<Bool>(get: {return !self.viewModel.MyProperty},
set: { p in self.viewModel.MyProperty = p})
{ SomeModalView()} }

Change value to opposite with exclamation mark Swift

Because putting an exclamation mark after a variable marks force unwrapping. In general, putting the exclamation mark after an expression means forcing something (force casting with as! or force unwrapping for optionals, etc.).

You have to put it before the value to negate a boolean expression.

(viewModel.arrValues[row] as! TestItem).isChecked = !((viewModel.arrValues[row] as? TestItem)?.isChecked)

Checking the value of an Optional Bool

With optional booleans it's needed to make the check explicit:

if boolean == true {
...
}

Otherwise you can unwrap the optional:

if boolean! {
...
}

But that generates a runtime exception if boolean is nil - to prevent that:

if boolean != nil && boolean! {
...
}

Before beta 5 it was possible, but it has been changed as reported in the release notes:

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

Addendum: as suggested by @MartinR, a more compact variation to the 3rd option is using the coalescing operator:

if boolean ?? false {
// this code runs only if boolean == true
}

which means: if boolean is not nil, the expression evaluates to the boolean value (i.e. using the unwrapped boolean value), otherwise the expression evaluates to false

Transforming property values while setting up binding in RX Swift iOS

You should use map:

viewModel.isIndividualActivity
.map(!)
.bind(to: individualView.rx.isHidden)
.disposed(by: self.disposeBag)

viewModel.isIndividualActivity
.map { isActivity -> CGFloat in
isActivity ? 40 : 0 //example values
}
.bind(to: pointViewTopConstraint.rx.constant)
.disposed(by: self.disposeBag)

Want to invert BOOL value in iOS sdk

You can't cast id to BOOL. Assuming it is stored correctly, the way you get it out of a dictionary is through the number wrapper NSNumber.

NSNumber *boolWrapper = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"ABC"];
return ![boolWrapper boolValue];

This will return 0 for 1 and 1 for 0.

If you simply cast it like you are doing, it will always be true unless the object doesn't exist (i.e. it is nil).

How Can I Save A Boolean In NSDefaults When A Button Is Pressed?

Create an IBAction for your button and do the NSUserDefault section below.

NSUserDefault

I always like to register my NSUserDeafult to default setting, a lot of people just continue with the second step without registering.

Register NSUserDefault in AppDelgate.swift

NSUserDefaults.standardUserDefaults().registerDefaults(["valueName": AnyObject])

Set Value to your NSUserDefault, this depends on what type of data you're storing, should match the one with your registration if you did register. (Example of Boolean data type below)

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "valueName") //Bool Data Type

Make sure you synchronize once you set the value to the NSUserDefault, this way it will update instantly, otherwise it will update when it get a chance.

NSUserDefaults.standardUserDefaults().synchronize()

Receive Value: this will receive boolean value since we set boolean and register boolean.

let Variable: Bool! = NSUserDefaults.standardUserDefaults().boolForKey("valueName")

How to assert the value of an optional Bool in Swift unit test?

The cleanest approach I found is:

XCTAssertEqual(firstArgumentInClosure, true)

Or if I want to assert it's false:

XCTAssertEqual(firstArgumentInClosure, false)

This doesn't require unwrapping the optional.



Related Topics



Leave a reply



Submit