iOS-Swift 中的循环
// for in 循环 for num in 0...3 { print(num) } // 0 // 1 // 2 // 3 let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { print("Hello, \(name)!") } // Hello, Anna! // Hello, Alex! // Hello, Brian! // Hello, Jack! // 字典也可以直接使用 for-in 循环: let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { print("\(animalName)s have \(legCount) legs") } // cats have 4 legs // ants have 6 legs // spiders have 8 legs
forEach 循环
(0...3).forEach { num in print(num) } // 0 // 1 // 2 // 3 let names = ["Anna", "Alex", "Brian", "Jack"] names.forEach { name in print("Hello, \(name)!") } // Hello, Anna! // Hello, Alex! // Hello, Brian! // Hello, Jack! let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs.forEach { (animalName, legCount) in print("\(animalName)s have \(legCount) legs") } // cats have 4 legs // ants have 6 legs // spiders have 8 legs
for-in 和 forEach 的区别
break
和continue
两个退出循环的关键字在 forEach 中不可用- 在 forEach 中使用 return 关键字,只会退出当前循环,不会退出外层的函数
与 forEach
不同的是,for-in
还可以跟 where
关键字一起使用,比如,在一个数字区间的循环中,我只想打印偶数:
for number in 0...9 where number.isMultiple(of: 2) { print(number) } // 0 // 2 // 4 // 6 // 8
While 循环
var number = 0 while number < 3 { print(number) number += 1 } // 0 // 1 // 2