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值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今早 泡菜:我腰好痛(┯_┯) 火锅:为什么?→_→ 泡菜:睡觉睡得腰痛~ 火锅:睡觉你都能腰痛→_→ 泡菜:睡觉...
    初九日阅读 2,622评论 0 0
  • 一个周就这么在不知不觉中度过。 今早虽然雾气笼罩中,但也注定今天是个阳光灿烂微风轻拂的日子。 为了让早餐丰富营养,...
    明懿妈妈阅读 1,850评论 0 0
  • 中考成绩以中等的成绩考上了县城里的一所高中。新生报到的第一天,我的父母也跟其他父母一样,把我连人带行李一起运到到学...
    小棉袄呀阅读 4,589评论 0 2
  • 你现在的气质里,藏着你走过的路,读过的书,写过的字。 哪怕你没有富庶的日子,也会有富庶的生命,强大的心理。 毛姆说...
    吴蕙兰阅读 7,222评论 0 0

友情链接更多精彩内容