Swift For-in循环

Swift For-in循环

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程