Swift Ternary conditional operation

Source: Internet
Author: User


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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.