📜  Swift for-in循环

📅  最后修改于: 2021-01-11 07:40:12             🧑  作者: Mango

快速循环

Swift For-in循环用于运行一组任务一定次数。此循环会重复执行多次。

例如

如果要编写一个打印“ Hello JavaTpoint”的语法,则简单语法为:

print("Hello JavaTpoint") 

如果您必须写相同的打印语句5次,该怎么办?简单的解决方案是:

print("Hello JavaTpoint") 
print("Hello JavaTpoint") 
print("Hello JavaTpoint") 
print("Hello JavaTpoint") 
print("Hello JavaTpoint") 

但是,有一种解决方案。您可以使用for-in循环来打印相同的语句并使代码更短。

for i in 1...5 {
//It will print Hello JavaTpoint for 5 times on the screen
print("Hello JavaTpoint")
}

范例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