moka2258 moka2258 - 11 months ago 48
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


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
. Anyone can read 'checkA()' and just know what it mean but people(or maybe just me) will need to think about what happen in

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

Answer Source

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.