So in Objective-C when using Booleans it's possible, and encouraged, to write code using a variable's non-zero value as it's boolean value, which means you can write code like this:
if (someBool) {
// Stuff
}
Also, there are reasons why code like the following is discouraged:
if (someBool == YES) {
// Might run into problems here
}
The reasons why checking a boolean against another boolean are better explained here, but briefly the issue is just that when you're comparing equality to YES
or NO
directly, you're actually comparing against 1
and 0
, respectively. Since Objective-C allows for using non-zero values as a truth value, you could end up comparing something that should be considered true against YES
and have the expression resolve to NO
, e.g.
int trueNumber = 2;
if (trueNumber == YES) {
// Doesn't run because trueNumber != 1
}
Is this still an issue in Swift? Code style issues aside, if I see something like the following
var someBool = true
if someBool == true {
// stuff
}
is that going to be an issue, or does it not really matter? Are these C-style comparisons still happening under the hood, or is there something built into the Swift BooleanType that prevents these issues?
Bool represents Boolean values in Swift. Create instances of Bool by using one of the Boolean literals true or false , or by assigning the result of a Boolean method or operation to a variable or constant.
result will be 1 if condition is true, 0 is condition is false.
Swift recognizes a value as boolean if it sees true or false . You can implicitly declar a boolean variable let a = false or explicitly declare a boolean variable let i:Bool = true .
The if <something> {}
structure in Swift requires the <something>
to conform to the BooleanType
protocol which is defined like this:
public protocol BooleanType {
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool { get }
}
If the type doesn't conform to this protocol, a compile-time error is thrown. If you search for this protocol in the standard library you find that the only type that conforms to this protocol is Bool
itself. Bool
is a type that can either be true
or false
. Don't think of it as the number 1
or 0
, but rather as On/Off Right/Wrong.
Now this protocol can be conformed to by any nominal type you want, e.g.:
extension Int : BooleanType {
public var boolValue : Bool {
return self > 0
}
}
Now if you do this (you shouldn't honestly), you're defining it by yourself what "True" and "False" means. Now you'd be able to use it like this (again, don't do this):
if 0 {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With