使用if 或者 swith進行條件判斷,
使用for-in,while,和 repeat-while進行循環
if 后面的()是可選的【例如下邊的 if score > 50】,但是其后的{}必須有(非可選)
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
注意:條件判斷中,描述必須是一個明確的bool值,不能含蓄的跟0作比較。也就是必須是yes或者no,不能跟0還是非0做參考
optionals
/You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional./
用國人的話來說就是:如果一個變量可能有值,也可能沒有值,就在初始化的時候添加一個問號?。
另外,聲明變量的時候不添加?,編譯不通過
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = nil"John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
print(greeting)
}else{
print("your name is nil")
}
?? 如果第一個為nil,就選擇 ?? 后邊的值
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
print(informalGreeting)
Switch
/Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality./
支持各種數據類型,以及更多的變量對比(只要符合條件就執行)
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)?") Is it a spicy red pepper?
default:
print("Everything tastes good in soup.")
}
注意:
1.注釋default報錯:Switch must be exhaustive(詳盡)
2.case后邊不再有break,只要滿足了一個case,程序就不會再去判斷其他case并執行
是否for-in遍歷字典的時候,因為字典是無序的集合,因此取出的keys也是任意的順序的
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
var lagestName:String? = nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
lagestName = kind
}
}
}
print(lagestName)
print(largest)
/* 注意:print(lagestName)會有警告,fix的方案有三:
1.print(lagestName ?? <#default value#>)
2.print(lagestName!)
3.print(lagestName as Any)
*/
Use while to 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.
var n = 2
while n < 100 {
n *= 2
}
print(n) 128
var m = 2
repeat {
m *= 2
} while m < 100
print(m) 128
使用 ..< 表示某個索引的范圍
var total = 0
for i in 0..<4 {
total += i
}
print(total) 6
使用 ... 表示某個索引的范圍【包含最后一個范圍,即:(0..<=4)這個表達式寫法是錯的,這里就是表達這個意思而已】
var total2 = 0
for i in 0...4 {
total2 += i
}
print(total2) 10