# swift 控制流

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

var teamScore = 0

for score in individualScores {

if score > 50{

teamScores += 3

}

else {

teamScores += 1

}

}

teamScore

var optionalString: String? = “Hello”

optionalString == nil

var optionalName: String? = “John Appleseed”

var greeting = “Hello!”

if let name = optionalName {

greeting = “Hello, \(name)”

}

Note

switch 支持多种数据以及多种比较，不限制必须是整数和测试相等。

let vegetable = “red pepper”

switch vegetable {

case “celery”:

let vegetableComment = “Add some raisins and make ants on a log.”

case “cucumber”, “watercress”:

let vegetableComment = “That would make a good tea sandwich.”

case let x where x.hasSuffix(“pepper”):

let vegetableComment = “Is it a spicy \(x)?”

default: //by gashero

let vegetableComment = “Everything tastes good in soup.”

}

Note

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

}

}

}

Note

var n = 2

while n < 100 { n = n * 2 } n var m = 2 do { m = m * 2 } while m < 100 m 你可以在循环中保持一个索引，通过 ".." 来表示索引范围或明确声明一个初始值、条件、增量。这两个循环做相同的事情: var firstForLoop = 0 for i in 0..3 { firstForLoop += i } firstForLoop var secondForLoop = 0 for var i = 0; i < 3; ++i { secondForLoop += 1 } secondForLoop 使用 .. 构造范围忽略最高值，而用 ... 构造的范围则包含两个值。

Posted in 未分类