1 The speciality of ternary conditional operation is that it is an operator with three operands, its prototype is the problem? Answer 1: Answer 2. It succinctly expresses the operation to choose one according to whether the question is established or not. If the question is true, return the result of answer 1; if not, return the result of answer 2.
2 The use of ternary conditional operations simplifies the following code:
3 if question: {
4 answer1
5}
6 else {
7 answer2
8 }
9 Here is an example of calculating the row height of a table. If there is a header, the row height should be 50 pixels higher than the content height; if there is no header, just 20 pixels higher.
10 let contentHeight = 40
11 let hasHeader = true
12 let rowHeight = contentHeight + (hasHeader? 50: 20)
13 // rowHeight is now 90
14 Writing this way will be more concise than the following code:
15 let contentHeight = 40
16 let hasHeader = true
17 var rowHeight = contentHeight
18 if hasHeader {
19 rowHeight = rowHeight + 50
20} else {
21 rowHeight = rowHeight + 20
twenty two }
23 // rowHeight is now 90
24 The first code example uses ternary conditional operations, so one line of code will give us the correct answer. This is much simpler than the second piece of code, without the need to define rowHeight as a variable, because its value does not need to be changed in the if statement.
25 Ternary conditional operations provide an efficient and convenient way to express alternative choices. It should be noted that excessive use of ternary conditional operations will change from concise code to difficult code. We should avoid using multiple ternary conditional operators in a combined statement.
Swift Ternary conditional operation