今天繼續(xù)學(xué)習(xí) Swift 的課程掰吕,這個課有 100 多課版保,我基本上都保證不了一天一課……比較郁悶拔匦Α!
今天學(xué)習(xí)的是循環(huán)控制的內(nèi)容彻犁,與其他語言類似叫胁。
for-in 循環(huán)
使用 for-in 循環(huán)來遍歷序列,比如一個范圍的數(shù)字汞幢,數(shù)組中的元素或者字符串中的字符
// 遍歷輸出 0 1 2 3
for i in 0...3 {
print(i)
}
// 輸出逐個的字符
foc c in "Hello,World" {
print(c)
}
for-in 遍歷字典
當(dāng)字典遍歷時驼鹅,每一個元素都返回一個(key, value)元組,你可以在 for-in 循環(huán)體中使用顯式命名常量來分解(key, value)元組成員
for-in 循環(huán)
如果不需要序列的每一個值森篷,可以使用下劃線來取代遍歷名以忽略值
for-in 分段區(qū)間
- 使用 stride(from:to:by:) 函數(shù)來跳過不想要的標(biāo)記(開區(qū)間)
- 閉區(qū)間也同樣適用输钩,使用 stride(from:through:by:)即可
在 Swift 中可以指定開區(qū)間和閉區(qū)間,可以避免部分的邊界問題仲智,我覺得這個比較好一些
while 循環(huán)
repeat-while 循環(huán)
示例代碼
把上面的關(guān)于字典遍歷买乃,開閉區(qū)間循環(huán),repeat-while 循環(huán)钓辆,用代碼進行演示
let dict = ["spider": 8, "ant": 6, "cat": 4]
for item in dict {
// 輸出元組
print(item)
// 輸出 key value
print("\(item.key) has \(item.value) legs")
}
for (animalName, legCount) in dict {
// 輸出兩個變量的值
print("\(animalName) has \(legCount) legs")
}
// 閉區(qū)間
for i in stride(from: 0, to: 50, by: 5) {
print(i)
}
// 開區(qū)間
for i in stride(from: 0, through: 50, by: 5) {
print(i)
}
let base = 3
let power = 5
var result = 1
// 這里循環(huán)時剪验,只是循環(huán)一個固定的次數(shù),省略掉了類似 C 語言中的循環(huán)計數(shù)變量
for _ in 1...power {
result *= base
}
// 243
print(result)
// repeat-while 循環(huán)
var count = 0
repeat {
print(count)
count += 1
} while count < 5
我的微信公眾號:“碼農(nóng)UP2U”