Swift 3.0中文版(2)控制流

Useifandswitchto make conditionals, and usefor-in,for,while, andrepeat-whileto make loops.

Parentheses around the condition or loop variable are optional. Braces around the body are required.

使用if和switch來進(jìn)行條件操作,使用for-in、for、while和repeat-while來進(jìn)行循環(huán)。包裹條件和循環(huán)

變量括號(hào)可以省略,但是語句體的大括號(hào)是必須的。

let individualScores = [75, 43, 103, 87, 12]

var teamScore = 0

for score in individualScores {

if score > 50 {

teamScore += 3

} else {

teamScore += 1

}

}

print(teamScore)

In anifstatement, the conditional must be a Boolean expression—this means that code such asif score {

... }is an error, not an implicit comparison to zero.

在if語句中,條件必須是一個(gè)布爾表達(dá)式——這意味著像if score { ... }這樣的代碼將報(bào)錯(cuò),而不會(huì)隱形地

與 0 做對比。

You can useifandlettogether to work with values that might be missing. These values are represented as

optionals. An optional value either contains a value or containsnilto indicate that a value is missing. Write a

question mark (?) after the type of a value to mark the value as optional.

你可以一起使用if和let來處理值缺失的情況。這些值可由可選值來代表。一個(gè)可選的值是一個(gè)具體的值或者

是nil以表示值缺失。在類型后面加一個(gè)問號(hào)來標(biāo)記這個(gè)變量的值是可選的。

var optionalString: String? = "Hello"

print(optionalString == nil)

var optionalName: String? = "John Appleseed"

var greeting = "Hello!"

if let name = optionalName {

greeting = "Hello, \(name)"

}

EXPERIMENT

ChangeoptionalNametonil. What greeting do you get? Add anelseclause that sets a different greeting ifoptionalNameisnil.

練習(xí): 把optionalName改成nil,greeting會(huì)是什么?添加一個(gè)else語句,當(dāng)optionalName是nil時(shí)給gre

eting賦一個(gè)不同的值。

If the optional value isnil, the conditional isfalseand the code in braces is skipped. Otherwise, the optional

value is unwrapped and assigned to the constant afterlet, which makes the unwrapped value available inside

the block of code.

如果變量的可選值是nil,條件會(huì)判斷為false,大括號(hào)中的代碼會(huì)被跳過。如果不是nil,會(huì)將值賦給let后面的常量,這樣代碼塊中就可以使用這個(gè)值了。

Another way to handle optional values is to provide a default value using the??operator. If the optional value

is missing, the default value is used instead.

另一種處理可選值的方法是通過使用 ?? 操作符來提供一個(gè)默認(rèn)值。如果可選值缺失的話,可以使用默認(rèn)值來代替。

let nickName: String? = nil

let fullName: String = "John Appleseed"

let informalGreeting = "Hi \(nickName ?? fullName)"

Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers

and tests for equality.

switch支持任意類型的數(shù)據(jù)以及各種比較操作——不僅僅是整數(shù)以及測試相等。

let vegetable = "red pepper"

switch vegetable {

case "celery":

print("Add some raisins and make ants on a log.")

case "cucumber", "watercress":

print("That would make a good tea sandwich.")

case let x where x.hasSuffix("pepper"):

print("Is it a spicy \(x)?")

default:

print("Everything tastes good in soup.")

}

EXPERIMENT

Try removing the default case. What error do you get?

練習(xí): 刪除default語句,看看會(huì)有什么錯(cuò)誤?

Notice howletcan be used in a pattern to assign the value that matched the pattern to a constant.

After executing the code inside the switch case that matched, the program exits from the switch statement.

Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end

of each case’s code.

注意let在上述例子的等式中是如何使用的,它將匹配等式的值賦給常量x。

運(yùn)行switch中匹配到的子句之后,程序會(huì)退出switch語句,并不會(huì)繼續(xù)向下運(yùn)行,所以不需要在每個(gè)子句結(jié)尾

寫break。

You usefor-into iterate over items in a dictionary by providing a pair of names to use for each key-value pair.

Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.

你可以使用for-in來遍歷字典,需要兩個(gè)變量來表示每個(gè)鍵值對。字典是一個(gè)無序的集合,所以他們的鍵和值以

任意順序迭代結(jié)束。

let interestingNumbers = [

"Prime": [2, 3, 5, 7, 11, 13],

"Fibonacci": [1, 1, 2, 3, 5, 8],

"Square": [1, 4, 9, 16, 25],

]

var largest = 0

for (kind, numbers) in interestingNumbers {

for number in numbers {

if number > largest {

largest = number

}

}

}

print(largest)

EXPERIMENT

Add another variable to keep track of which kind of number was the largest, as well as what that largest

number was.

練習(xí): 添加另一個(gè)變量來記錄最大數(shù)字的種類(kind),同時(shí)仍然記錄這個(gè)最大數(shù)字的值。

Usewhileto repeat a block of code until a condition changes. The condition of a loop can be at the end

instead, ensuring that the loop is run at least once.

使用while來重復(fù)運(yùn)行一段代碼直到不滿足條件。循環(huán)條件也可以在結(jié)尾,保證能至少循環(huán)一次。

var n = 2

while n < 100 {

n=n* 2

}

print(n)

var m = 2

repeat {

m=m* 2

} while m < 100

print(m)

You can keep an index in a loop by using..< to make a range of indexes.

你可以在循環(huán)中使用..<來表示范圍。

var total = 0

for i in 0..<4 {

total += i

}

print(total)

Use..< to make a range that omits its upper value, and use...to make a range that includes both values.

使用..<創(chuàng)建的范圍不包含上界,如果想包含的話需要使用...。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容