循環(huán)結構
- 案例代碼如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//開區(qū)間[0,5)
for i in 0..<5 {
print(i)
}
print("------")
//閉區(qū)間[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)
}
}
閉區(qū)間運算符:a...b 等價于[a,b]
半開區(qū)間運算符:a..<b 等價于[a,b)
for i in 0...5
:閉區(qū)間[0,5]遍歷晰赞;let r1 = 0..<9
:打印結果為:0..<9
let r2 = 0...9
:打印結果為:0...9
while i < 10
:寫在前面的可以省略小括號()repeat - while
用法 相當于OC中的do-while在for循環(huán)中如果沒有使用到i磷支,可以使用
_
忽略代碼如下:
for _ in 0...3 {
print("li")
}
for -- 區(qū)間運算符用在數(shù)組上
- 單側區(qū)間:讓區(qū)間朝一個方向盡可能的遠疮跑;
- 代碼案例:
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,+∞)泡躯,但由于數(shù)組長度的限制,最終表示[2,4]
...2丽焊,表示(-∞,2]较剃,但由于數(shù)組長度的限制,最終表示[0,2]
..<2技健,表示(-∞,2)写穴,但由于數(shù)組長度的限制,最終表示[0,2)
再看一段代碼:
let range = ...5
range.contains(7) //false
range.contains(4) //true
range.contains(-3)//true
- ...5:表示(-∞,5]雌贱,所以7不在此區(qū)間之內啊送,4和-3在此區(qū)間之內;
區(qū)間類型
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
}
}
- 字符欣孤,字符串也能使用區(qū)間運算符馋没,但默認不能用在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
}
}
帶間隔的區(qū)間值
- 案例代碼如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let value1 = 11
let interval = 2
//打印出 從4到11降传,間隔為2 的所有數(shù)值
for value in stride(from: 4, through: value1, by: interval) {
print(value)
}
}
}
- 打印出 從4到11披泪,間隔為2 的所有數(shù)值,輸出結果為:4搬瑰,6款票,8控硼,10;