Swift - 区间运算符

注:代码已升级至Swift4

区间运算符可以用来表示两个操作数之间的范围集合。

闭区间运算符:a…b

1
2
3
for iCount in 1...10 {
//从1遍历到10(包括10)
}

半闭区间运算符:a..<b

1
2
3
4
5
var fruts = ["apple","orange","banana"]
let iCount = fruts.count
for i in 0..<iCount {
print("第\(i+1)个水果是\(fruts[i])")
}

倒序循环

通过 reversed() 方法,我们可以将一个正序循环变成逆序循环。

1
2
3
for i in (0..<10).reversed() {
print(i)
}

字符串范围也可以使用区间运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//字符串截取
let words = "appblog.cn"

//不使用区间运算符
let index1 = words.index(words.startIndex, offsetBy: 4)
let index2 = words.index(words.startIndex, offsetBy: 6)
let range = Range(uncheckedBounds: (lower: index1, upper: index2))
let rangeStr = words.substring(with: range) //lo
print(rangeStr)

//使用区间运算符
let range2 = words.index(words.startIndex, offsetBy: 4)..<words.index(words.startIndex, offsetBy: 6)
let rangeStr2 = words.substring(with: range2) //lo
print(rangeStr2)

Comparable

区间运算符除了返回一个Range外,还可以接受Comparable的输入,返回ClosedInterval或HalfOpenInterval

可以用这个特性检查字符串里的字符是不是都是合法字符(比如是不是都是小写)

1
2
3
4
5
6
7
8
let words = "AppBlog.CN"

let interval = "a"..."z"
for c in words.characters {
if !interval.contains(String(c)) {
print("\(c)不是小写字母")
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :