Conditionals in Swift
在之前的章节代码相对simple life: you declared some simple constants and variables and then assigned them values. But of course, an application really comes to life – and programming becomes a bit more challenging – when the application makes decisions based on the contents of its variables. For example, a game may let players leap a tall buildingifthey have eaten a power-up. You use conditional statements to help applications make these kind of decisions.
if/else
if/elsestatements execute code based on a specific logical condition. You have a relatively simple either/or situation and depending on the result one branch of code or another (but not both) runs. Consider Knowhere, your small town from the previous chapter, and imagine that you need to buy stamps. Either Knowhere has a post office or it does not. If it has a post office, you will buy stamps there. If it does not have a post office, you will need to drive to the next town to buy stamps. Whether there is a post office is your logical condition. The different behaviors are “get stamps in town” and “get stamps out of town.”
Some situations are more complex than a binary yes/no. You will see a more flexible mechanism calledswitchin Chapter 5. But for now, let’s keep it simple.
Create a new OS X playground and name itConditionals. Enter the code below, which shows the basic syntax for anif/elsestatement:
Listing 3.1 Big or small?
import Cocoavar population: Int = 5422var message: Stringif population < 10000 {message = "\(population) is a small town!"} else {message = "\(population) is pretty big!"}print(message)
You first declarepopulationas an instance of theInttype and then assign it a value of 5422. Next, you declare a variable calledmessagethat is of theStringtype. You leave this variable uninitialized at first, meaning that you do not assign it a value.
Next comes the conditionalif/elsestatement. This is wheremessageis assigned a value based on whether the “if” statement evaluates to true. (Notice that you usestring interpolationto put the population into themessagestring.)
Figure 3.1shows what your playground should look like. The console and the results sidebar show thatmessagehas been set to be equal to the string literal assigned when the conditional evaluates to true. How did this happen?
Figure 3.1Conditionally describing a town’s population
The condition in theif/elsestatement tests whether your town’s population is less than 10,000 via the<comparison operator. If the condition evaluates to true, thenmessageis set to be equal to the first string literal (“X is a small town!”). If the condition evaluates to false – if the population is 10,000 or greater – themessageis set to be equal to the second string literal (“X is pretty big!”). In this case, the town’s population is less than 10,000, somessageis set to “5422 is a small town!”
Table 3.1 lists Swift’s comparison operators.
Table 3.1 Comparison operators
Operator |
Description |
< |
Evaluates whether the number on the left is smaller than the number on the right. |
<= |
Evaluates whether the number on the left is smaller than or equal to the number on the right. |
> |
Evaluates whether the number on the left is greater than the number on the right. |
>= |
Evaluates whether the number on the left is greater than or equal to the number on the right. |
== |
Evaluates whether the number on the left is equal to the number on the right. |
!= |
Evaluates whether the number on the left is not equal to the number on the right. |
=== |
评估是否two instances point to the same reference. |
!== |
评估是否two instances do not point to the same reference. |
You do not need to understand all of the operators’ descriptions right now. You will see many of them in action as you move through the book, and they will become clearer as you use them. Refer back to this table as a reference if you have questions.
Sometimes you only care about one aspect of the condition that is under evaluation. That is, you want to execute code if a certain condition is met and do nothing if it is not. Enter the code below. (Notice that new code, shown in bold, appears in two places.)
清单3.2有职位office?
import Cocoa var population: Int = 5422 var message: Stringvar hasPostOffice: Bool = true如果数量< 10000{消息= " \(人口)is a small town!" } else { message = "\(population) is pretty big!" } print(message)if !hasPostOffice {print("Where do we buy stamps?")}
Here, you add a new variable calledhasPostOffice. This variable has the typeBool, short for “Boolean.” Boolean types can take one of two values:trueorfalse. In this case, the BooleanhasPostOfficevariable keeps track of whether the town has a post office. You set it totrue, meaning that it does.
The!is called alogical operator. This operator is known as “logical not.” It tests whetherhasPostOfficeis false. You can think of!as inverting aBooleanvalue: true becomes false, and false becomes true.
The code above first setshasPostOfficeto true, then asks whether it is false. IfhasPostOfficeis false, you do not know where to buy stamps, so you ask. IfhasPostOfficeis true, you know where to buy stamps and do not have to ask, so nothing happens.
Because the towndoeshave a post office (becausehasPostOfficewas initialized totrue), the condition!hasPostOfficeis false. That is, it isnotthe case thathasPostOfficeis false. Therefore, theprint()function never gets called.
Table 3.2 lists Swift’s logical operators.
Table 3.2 Logical operators
Operator |
Description |
&& |
Logical AND: true if and only if both are true (false otherwise) |
|| |
Logical OR: true if either is true (false only if both are false) |
! |
Logical NOT: true becomes false, false becomes true |