For 循環(huán)還是比較有意思的钧大。
forLoop.swift
print("for i in 1..<5 runs 4 times")
for i in 1..<5 {
print(i)
}
print("")
print("for i in 1...5 runs 5 times")
for i in 1...5 {
print(i)
}
print("")
print("for _ in 1...2 runs 2 times and only care loop count but not the index in loop")
for _ in 1...2 {
print("printing _ here, it means nothing but loop, you can't use as \\(_)")
}
print("")
print("we can interate an array")
let a = [6, 5, 4, 3, 2, 1]
for i in a {
print(i)
}
print("")
print("use tuple can get much more info from for in")
let scores = ["Alice": 29, "John": 6, "Yahs": 90]
for (name, score) in scores {
print("\(name) gets \(score)")
}
print("")
print("only show values that index%2 is zero")
for (index, item) in a.enumerated().filter({
(index, item) in index % 2 == 0
}) {
print("[\(index)]\(item) ")
}
print("")
var x = [10, 3, 20, 15, 4]
print("x.sorted() is \(x.sorted())")
print("x.sorted().filter { $0 > 5 } is \(x.sorted().filter { $0 > 5 })")
print("x.sorted().filter { $0 > 5 }.map { $0 * 100 } is \(x.sorted().filter { $0 > 5 }.map { $0 * 100 })")
Terminal
運(yùn)行swift forLoop.swift
如下:
for i in 1..<5 runs 4 times
1
2
3
4
for i in 1...5 runs 5 times
1
2
3
4
5
for _ in 1...2 runs 2 times and only care loop count but not the index in loop
printing _ here, it means nothing but loop, you can't use as \(_)
printing _ here, it means nothing but loop, you can't use as \(_)
we can interate an array
6
5
4
3
2
1
use tuple can get much more info from for in
Yahs gets 90
Alice gets 29
John gets 6
only show values that index%2 is zero
[0]6
[2]4
[4]2
x.sorted() is [3, 4, 10, 15, 20]
x.sorted().filter { $0 > 5 } is [10, 15, 20]
x.sorted().filter { $0 > 5 }.map { $0 * 100 } is [1000, 1500, 2000]
關(guān)于enumerated()
參見官方文檔
“If you need the integer index of each item as well as its value, use the enumerated() method to iterate over the array instead. For each item in the array, the enumerated() method returns a tuple composed of the index and the value for that item. You can decompose the tuple into temporary constants or variables as part of the iteration”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3 beta).” iBooks.
其中filter
就是一個(gè)過濾华临,返回一個(gè)bool
值幽污。