For-in Loops in Swift3.0

For 循环还是比较有意思的。
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运行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] 

关于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就是一个过滤,返回一个bool值。

你可能感兴趣的:(For-in Loops in Swift3.0)