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

前端 未结 3 2091
南笙
南笙 2020-11-28 00:14

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

Here is the line...

backgroundView.layer.cornerRadius = self.isRounded ? frame.siz         


        
3条回答
  •  春和景丽
    2020-11-28 00:31

    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
    }
    

提交回复
热议问题