Tometoyou
Tometoyou

Reputation: 8376

How does Swift handle if statements?

If I have the statement:

if object != nil && object.property == 2 {
    //do something
}

does the if statement break as soon as it finds out object = nil?

Upvotes: -1

Views: 896

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

Yes

When you concatenate a list of conditions C[0]...C[n] with the AND && operator, the runtime evaluates in order each condition and if a C[i] condition is found false, then the evaluation of the whole expression does end and it is judged false.

let c0 = true
let c1 = false
let c2 = true

if c0 && c1 && c2 {
    print("Hello world")
}

In this case only c0 and c1 will be evaluated and the whole expression will be interpreted as false.

You can test it yourself in Playground.

enter image description here

c0 || c1 || c2

Symmetrically if you define an expression as the OR || concatenation of several clauses, then the whole expression is interpreted as true (and the evaluation of the clauses does stop) as soon as the first true condition gets found.

Upvotes: 1

Grimxn
Grimxn

Reputation: 22487

Yes is the answer.

Simple to try - see below - however note that as written your test won't work - a non-optional cannot be nil, and so you will have to unwrap it to test .property.

struct MyObj {
    var property: Int
}

var object: MyObj? = nil

if object != nil && object!.property == 2 {
    print("Not nil")
} else {
    print("Nil") // Prints - would have crashed if test fully evaluated
}

object = MyObj(property: 2)

if object != nil && object!.property == 2 {
    print("Not nil")  // Prints
} else {
    print("Nil")
}

Upvotes: 0

Related Questions