循环结构
- 案例代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//开区间[0,5)
for i in 0..<5 {
print(i)
}
print("------")
//闭区间[0,5]
for i in 0...5 {
print(i)
}
//Range<Int>
let r1 = 0..<9
print(r1)
let r2 = 0...9
print(r2)
var i = 0
while i < 10 {
i += 1
print(i)
}
print("-----")
var k = 10
repeat{
k -= 1
print(k)
}while(k > 0)
}
}
闭区间运算符:a...b 等价于[a,b]
半开区间运算符:a..<b 等价于[a,b)
for i in 0...5
:闭区间[0,5]遍历;let r1 = 0..<9
:打印结果为:0..<9
let r2 = 0...9
:打印结果为:0...9
while i < 10
:写在前面的可以省略小括号()repeat - while
用法 相当于OC中的do-while在for循环中如果没有使用到i,可以使用
_
忽略代码如下:
for _ in 0...3 {
print("li")
}
for -- 区间运算符用在数组上
- 单侧区间:让区间朝一个方向尽可能的远;
- 代码案例:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let arr = ["li","yanyan","xie","sf","tank"]
for name in arr[0...4] {
print(name)
}
print("-----")
for name in arr[2...] {
print(name)
}
print("-----")
for name in arr[...2] {
print(name)
}
print("-----")
for name in arr[..<2] {
print(name)
}
}
}
2... ,表示[2,+∞),但由于数组长度的限制,最终表示[2,4]
...2,表示(-∞,2],但由于数组长度的限制,最终表示[0,2]
..<2,表示(-∞,2),但由于数组长度的限制,最终表示[0,2)
再看一段代码:
let range = ...5
range.contains(7) //false
range.contains(4) //true
range.contains(-3)//true
- ...5:表示(-∞,5],所以7不在此区间之内,4和-3在此区间之内;
区间类型
ClosedRange<Int>
:1...3 ==> [1,3]Range<Int>
:1..<3 ==> [1,3)PartialRangeThrough<Int>
:...5 ==> (-∞,5]代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//ClosedRange<Int>
let range1 = 1...3
//Range<Int>
let range2 = 1..<3
//PartialRangeThrough<Int>
let range3 = ...5
}
}
- 字符,字符串也能使用区间运算符,但默认不能用在for-in中;
- 看一段代码:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let strRange1 = "cc"..."ff"
strRange1.contains("cb")//false
strRange1.contains("dz")//true
strRange1.contains("fg")//false
let strRange2 = "a"..."f"
strRange2.contains("d")//true
strRange2.contains("z")//false
//ASCII字符
let charRange:ClosedRange<Character> = "\0"..."~"
charRange.contains("G")//true
}
}
带间隔的区间值
- 案例代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let value1 = 11
let interval = 2
//打印出 从4到11,间隔为2 的所有数值
for value in stride(from: 4, through: value1, by: interval) {
print(value)
}
}
}
- 打印出 从4到11,间隔为2 的所有数值,输出结果为:4,6,8,10;