moka2258 moka2258 - 1 month ago 8
Swift Question

Return the bool statement directly VS using if to return bool

There is a question that I really want to ask for a really long time now.
Looking at the below code in Swift

import UIKit

var str = "Hello, playground"
var flag = true

func checkA() -> Bool{
if str == "Hello, playground" && flag == true {
return true
}
return false
}

func checkB() -> Bool{
return str == "Hello, playground" && flag == true
}

checkA()
checkB()


It is possible to see that 'checkA()' and 'checkB()' is basically the same function since it return the same value every time. In my opinion(I never was good at programming), I prefer 'checkA()' as it is more readable than
checkB()
. Anyone can read 'checkA()' and just know what it mean but people(or maybe just me) will need to think about what happen in
checkB()
.

Is there any performance advantage in using
checkB()
instead of
checkA()
or is this just a preference thing?

Answer

I don´t think it´s any performance changes in these, checkB() has lesser code and is much cleaner but more checkA() is more readable. It´s up to you what you prefer to use.