Deepak Terse
Deepak Terse

Reputation: 712

Swift - Best way to write an if else

I want to assign a boolean value to a variable based on a certain expression. Here's my code

Method 1 :

    if jobListView.tableView.jobIds.count > 0 {
        container.isHidden = false
    } else {
        container.isHidden = true
    }

Method 2 :

    container.isHidden = jobListView.tableView.jobIds.count <= 0

I understand that the second one is more readable but will it make any difference in execution speed.

Upvotes: 1

Views: 510

Answers (1)

Martin R
Martin R

Reputation: 540075

I understand that the second one is more readable

That is a good argument. Start with the version that you (or your team) are more comfortable with.

will it make any difference in execution speed?

As mentioned above – profile your app and find the performance bottlenecks. Then you can decide if this particular part needs to be improved.

In this particular case it won't make a difference at all, the compiler is smart enough to optimize both variants. Here is a simplified self-contained example: Both

var hidden = false

func foo(n: Int) {
    if n > 0 {
        hidden = false
    } else {
        hidden = true
    }
}

and

var hidden = false

func foo(n: Int) {
    hidden = n <= 0
}

generate the identical assembly code

    .private_extern __T04main3fooySi1n_tF
    .globl  __T04main3fooySi1n_tF
    .p2align    4, 0x90
__T04main3fooySi1n_tF:
    pushq   %rbp
    movq    %rsp, %rbp
    testq   %rdi, %rdi
    setle   __T04main6hiddenSbvp(%rip)
    popq    %rbp
    retq

as you can verify with

swiftc -O -emit-assembly main.swift

Upvotes: 7

Related Questions