user11100093
user11100093

Reputation:

Using ternary for if else

I’m having this if-else condition..

if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}

How can I use a ternary operator instead of this if-else condition..

I referred this link..but it didn’t help

Upvotes: 0

Views: 449

Answers (2)

Shiraz Khan
Shiraz Khan

Reputation: 41

You can break down it in to

theImage.contentMode = APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc ? .scaleAspectFill : .scaleToFill

Upvotes: 0

Larme
Larme

Reputation: 26026

For the inside if:

if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
   theImage.contentMode = .scaleAspectFill
} else {
   theImage.contentMode = .scaleToFill
}

Gives:

theImage.contentMode = (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill : . scaleToFill

Now, if we do the top level if:

theImage.contentMode = UIDevice.current.iPad ? insideIf : . scaleAspectFill

In full code:

theImage.contentMode = UIDevice.current.iPad ? (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill 
                                                                                                                                    : . scaleToFill 
                                             : . scaleAspectFill

That's not really redable.

But

if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}

Might be transformed into:

if UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) {
    theImage.contentMode = .scaleToFill
} else {
    theImage.contentMode = .scaleAspectFill
}

That's shorter, but might be harder to read.

With ternary if:

theImage.contentMode = UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleToFill : . scaleAspectFill

In my opinion? Keep your version (or maybe the version where I use only one if/else). Compiler will optimise nevertheless, and it's easier to fix/modify it two months later if you can grasp why and what it does quickly.

Upvotes: 1

Related Questions