Swift For-in循环用于运行一组任务一定次数。此循环会重复执行多次。
例如
如果要编写一个打印” Hello srcmini”的语法, 则简单语法为:
print("Hello srcmini")
如果你必须写相同的打印语句5次, 那会是什么?简单的解决方案是:
print("Hello srcmini")
print("Hello srcmini")
print("Hello srcmini")
print("Hello srcmini")
print("Hello srcmini")
但是, 有一种解决方案。你可以使用for-in循环来打印相同的语句并使代码更短。
for i in 1...5 {
//It will print Hello srcmini for 5 times on the screen
print("Hello srcmini")
}
范例1:
let names = ["Ajeet", "Aryan", "Ayan", "Alex"]
for name in names {
print("Good Morning \(name)")
}
输出
Good Morning Ajeet
Good Morning Aryan
Good Morning Ayan
Good Morning Alex
一个Swift程序, 用于打印特定编号的表(此处为5)。
for index in 1...10 {
print("\(index) times 5 is \(index * 5)")
}
输出
1 times 5 is 5
2 times 5 is 10
3 times 5 is 15
4 times 5 is 20
5 times 5 is 25
6 times 5 is 30
7 times 5 is 35
8 times 5 is 40
9 times 5 is 45
10 times 5 is 50
评论前必须登录!
注册