Swift学习22:如何在Swift里进行循环控制

张建 lol

for in 循环

  • 使用 for in 循环来遍历序列,比如一个范围的数字,数组中元素或者字符串中的字符

  • 如果你不需要序列的每一个值,你可以使用下划线 _ 来取代遍历名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 遍历
for i in 0...3{
print(i)
}

// 遍历字符串
for c in "hello,world" {
print(c)
}

// 遍历数组
let letter = ["a","b","c"]
for str in letter {
print(str)
}

for in 遍历字典

  • 当遍历字典时,每一个元素都返回一个 (key,value) 元组,你可以在 for in 循环体中使用显示命名常量来分解 (key,value) 元组成员
1
2
3
4
5
6
7
let nums = ["age":"30","sex":"男"]
for (key,value) in nums {
print("key is \(key),value is \(value)")
}
for t in nums {
print("key is \(t.0),value is \(t.1)")
}

for in 分段区间

  • 使用 stride(from:to:by) 函数来跳过不想要的标记(开区间
1
2
3
for i in stride(from: 0, to: 50, by: 10) {
print(i)
}

  • 闭区间 也同样适用,使用 stride(from:through:by:) 即可
1
2
3
for i in stride(from: 0, through: 50, by: 10) {
print(i)
}

while 循环

  • repeat-while 循环 (oc 中是 do-while
  • Post title:Swift学习22:如何在Swift里进行循环控制
  • Post author:张建
  • Create time:2023-02-23 21:34:50
  • Post link:https://redefine.ohevan.com/2023/02/23/Swift课程/Swift学习22:如何在Swift里进行循环控制/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
On this page
Swift学习22:如何在Swift里进行循环控制