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来进行条件操作,使用for-in、for、while和repeat-while来进行循环。包裹条件和循环

变量括号可以省略,但是语句体的大括号是必须的。

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语句中,条件必须是一个布尔表达式——这意味着像if score { ... }这样的代码将报错,而不会隐形地

与 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来处理值缺失的情况。这些值可由可选值来代表。一个可选的值是一个具体的值或者

是nil以表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。

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.

练习: 把optionalName改成nil,greeting会是什么?添加一个else语句,当optionalName是nil时给gre

eting赋一个不同的值。

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,条件会判断为false,大括号中的代码会被跳过。如果不是nil,会将值赋给let后面的常量,这样代码块中就可以使用这个值了。

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.

另一种处理可选值的方法是通过使用 ?? 操作符来提供一个默认值。如果可选值缺失的话,可以使用默认值来代替。

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支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。

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?

练习: 删除default语句,看看会有什么错误?

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。

运行switch中匹配到的子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾

写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来遍历字典,需要两个变量来表示每个键值对。字典是一个无序的集合,所以他们的键和值以

任意顺序迭代结束。

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.

练习: 添加另一个变量来记录最大数字的种类(kind),同时仍然记录这个最大数字的值。

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来重复运行一段代码直到不满足条件。循环条件也可以在结尾,保证能至少循环一次。

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.

你可以在循环中使用..<来表示范围。

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.

使用..<创建的范围不包含上界,如果想包含的话需要使用...。

你可能感兴趣的:(Swift 3.0中文版(2)控制流)