let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
在if裏面,判斷式必須要是布林表示,所以 if a{....}這樣的方式會錯誤,a不會自動和0做比較。
for...in也可以用在dictionary上,例如
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
}
}
}
可以用...來表示範圍,例如var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
沒有留言:
張貼留言