Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Boolean checking

Tags:

swift

boolean

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?

like image 631
Ziewvater Avatar asked Oct 01 '15 16:10

Ziewvater


People also ask

What is a boolean Swift?

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.

Is 0 true or false in Swift?

result will be 1 if condition is true, 0 is condition is false.

How do I return true or false in Swift?

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 .


1 Answers

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 {
    ...
}
like image 89
Kametrixom Avatar answered Sep 28 '22 23:09

Kametrixom