Evaluate Bool property of optional object in if statement
Ah, found it:
if objectWithBool?.bool == true {
// objectWithBool != nil && bool == true
} else {
// objectWithBool == nil || bool == false
}
The optional chaining expression objectWithBool?.bool
returns an optional Bool
. Since it is optional, that expression alone in the if
statement would be evaluated to true
/false
based on whether the optional contains a value or not.
By using the ==
operator the if
statement checks the optional's value, which in this case can be true
, false
, or nil
.
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
How to do an action if an optional boolean is true?
For good order
if (spouseIsMale.orElse(false)) {
System.out.println("There is a male spouse.");
}
Clear.
Best way to check for nullable bool in a condition expression (if ...)
I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null
Or if you want more options...
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null
(nullableBool == true)
will never return true if the bool? is null :P
What's wrong with comparing non-optional bool in a single if structure in swift
A bit of history...
In Swift 1.0, it was possible to check if an optional variable optVar
contained a value by just checking:
if optVar {
println("optVar has a value")
} else {
println("optVar is nil")
}
In The Swift Programming Language, the update for Swift 1.1 (dated 2014-10-16) stated:
Optionals no longer implicitly evaluate to
true
when they have a value andfalse
when they do not, to avoid confusion when working with optionalBool
values. Instead, make an explicit check againstnil
with the==
or!=
operators to find out if an optional contains a value.
So, the nonsensical error message that you are getting was put there because the Swift compiler is interpreting your:
if a {
}
to mean:
if a != nil {
}
and it is encouraging you to test against nil
to determine if the Optional a
has a value.
Perhaps the Swift authors will change it in the future, but for now you will have to explicitly unwrap a
:
if a! {
}
or check against true
:
if a == true {
}
or (to be completely safe):
if a ?? false {
print("this will not crash if a is nil")
}
Use of Boolean? in if expression
You can compare nullable boolean with true
, false
or null
using equality operator:
var b: Boolean? = null
if (b == true) {
// b was not null and equal true
}
if (b == false) {
// b is false
}
if (b != true) {
// b is null or false
}
How does let evaluate a bool value in Swift?
In addition to Bools, if
statements can also take optionals, with the condition evaluating to whether or not the optional has a value. This particular construct is called "optional binding".
Check if null Boolean is true results in exception
When you have a boolean
it can be either true
or false
. Yet when you have a Boolean
it can be either Boolean.TRUE
, Boolean.FALSE
or null
as any other object.
In your particular case, your Boolean
is null
and the if
statement triggers an implicit conversion to boolean
that produces the NullPointerException
. You may need instead:
if(bool != null && bool) { ... }
Related Topics
How to Check Object Is Nil or Not in Swift
Dyld: Library Not Loaded: @Rpath/Libswiftcore.Dylib Problem with New Xcode (10.2)
How to Use Image Literal in Xcode 13
Timedmetadata' Deprecated. Another Method? <Updated>
How to Set a Specific Default Time for a Date Picker in Swift
Load a Collada (Dae) File into Scnnode (Swift - Scenekit)
How to Check If 'Any(Not Any)' Is Nil or Not in Swift
How Do Closures Capture Values from Previous Calls
Detail View Is Not Updated When the Model Is Updated (Using List) Swiftui
Get Url to a Local File with Spm (Swift Package Manager)
Error When Using Generic as Property Type in Swift
How to Rotate Object in a Scene with Pan Gesture - Scenekit
Swift Programmatically Set Segues
How to Make Protocol Associated Type Require Protocol Inheritance and Not Protocol Adoption
Detecting If Wifi or Bluetooth Is Turned on or Off by the User