import Foundation
//Swift中的遍历
//遍历字符串
let str = "Good Night!"
for i in str {
print(i)
}
//遍历数组
let arr = ["China","Japan","USA","German"]
for j in arr {
print(j)
}
//遍历数组的索引值和值
for (k,v) in arr.enumerated() {
print("The index \(k) is \(v)")
}
//遍历集合
var letters:Set = ["B","D","E","G","H","J"]
for item in letters {
print("The letter is : \(item)")
}
//遍历集合中的索引值和值
for setvalue in letters.enumerated() {
print("The set's key and value is :\(setvalue)")
}
//遍历字典的值
var names:[Int:String] = [1:"zhangsan",2:"lisi",5:"wanglili",8:"mengzhang"]
for namevalue in names.values {
print(namevalue)
}
//遍历字典的键
for namekey in names.keys {
print(namekey)
}
//遍历字典的键和值
for name in names {
print(name)
}
//例子: 求1+2+3+4+5.....100的和
var sum = 0
var currValue = 1
for _ in 1...100 {
sum = sum + currValue
currValue += 1
}
print(sum)
//练习: 打印 小九九
var x = 1
var y = 1
var xy = 0
for x in 1...9 {
for y in 1...x {
xy = x * y
print("\(x) * \(y) = \(xy) ", terminator: " ")
}
print("")
}
输出:
G
o
o
d
N
i
g
h
t
!
China
Japan
USA
German
The index 0 is China
The index 1 is Japan
The index 2 is USA
The index 3 is German
The letter is : H
The letter is : B
The letter is : G
The letter is : J
The letter is : D
The letter is : E
The set's key and value is :(offset: 0, element: "H")
The set's key and value is :(offset: 1, element: "B")
The set's key and value is :(offset: 2, element: "G")
The set's key and value is :(offset: 3, element: "J")
The set's key and value is :(offset: 4, element: "D")
The set's key and value is :(offset: 5, element: "E")
wanglili
lisi
zhangsan
mengzhang
5
2
1
8
(key: 5, value: "wanglili")
(key: 2, value: "lisi")
(key: 1, value: "zhangsan")
(key: 8, value: "mengzhang")
5050
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
Program ended with exit code: 0