justColbs
justColbs

Reputation: 1872

What is the `?` is or the `:` at the equation when coding in Swift

I have ran into a line of code in the infamous SevenSwitch class.

Here is the line...

backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2

I don't understand what the ? is or the : at the end of the equation. Could someone please explain what these mean and how they are used?

Upvotes: 1

Views: 243

Answers (3)

Greg
Greg

Reputation: 33650

That's the ternary operator

Basically it's saying "set the corner radius of the background view to 0.4 times the frame's height if rounded, otherwise set the corner radius to 2".

Upvotes: 7

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

Operators can be unary, binary, or ternary:

This is Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).

From Apple Documents Basic Operators

Ternary Conditional Operator

The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false. If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.

As per your question if isRound is true then corner radios is frame.size.height else it's 2.

As like if condition :

if(self.isRounded){
    backgroundView.layer.cornerRadius = frame.size.height * 0.4
}
else{
    backgroundView.layer.cornerRadius = 2.0
}

Upvotes: 5

Jojodmo
Jojodmo

Reputation: 23596

The ? and : are ternary operators. They are just shorthand for if statements.

An english translation of var a = b ? c : d where b is a boolean is set a equal to c if b is true, and to d if b is false.

So, for example,

backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2

can be translated into

if(self.isRounded){
    backgroundView.layer.cornerRadius = frame.size.height * 0.4
}
else{
    backgroundView.layer.cornerRadius = 2
}

Upvotes: 5

Related Questions