使用if 或者 swith進(jìn)行條件判斷翔悠,
使用for-in野芒,while,和 repeat-while進(jìn)行循環(huán)
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)
注意:條件判斷中,描述必須是一個(gè)明確的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./
用國(guó)人的話來(lái)說(shuō)就是:如果一個(gè)變量可能有值顷编,也可能沒(méi)有值,就在初始化的時(shí)候添加一個(gè)問(wèn)號(hào)媳纬?。
另外茅糜,聲明變量的時(shí)候不添加?蔑赘,編譯不通過(guò)
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")
}
?? 如果第一個(gè)為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./
支持各種數(shù)據(jù)類(lèi)型缩赛,以及更多的變量對(duì)比(只要符合條件就執(zhí)行)
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報(bào)錯(cuò):Switch must be exhaustive(詳盡)
2.case后邊不再有break,只要滿(mǎn)足了一個(gè)case辩昆,程序就不會(huì)再去判斷其他case并執(zhí)行
是否for-in遍歷字典的時(shí)候,因?yàn)樽值涫菬o(wú)序的集合汁针,因此取出的keys也是任意的順序的
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
標(biāo)記上面哪組擁有最大的數(shù)
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)會(huì)有警告砚尽,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
使用 ..< 表示某個(gè)索引的范圍
var total = 0
for i in 0..<4 {
total += i
}
print(total) 6
使用 ... 表示某個(gè)索引的范圍【包含最后一個(gè)范圍,即:(0..<=4)這個(gè)表達(dá)式寫(xiě)法是錯(cuò)的尉辑,這里就是表達(dá)這個(gè)意思而已】
var total2 = 0
for i in 0...4 {
total2 += i
}
print(total2) 10