1,闭区间运算符:a...b
for iCount in 10...100{ //从10遍历到100(包括100) }
2,半闭区间运算符:a..<b
var fruts = ["apple","orange","banana"] let iCount = fruts.count for i in 0 ..< iCount{ print("第(i+1)个水果是(fruts[i])") }
3,倒序循环
for i in (0..<10).reversed() { print(i) }
4,字符串范围也可以使用区间运算符
//字符串截取 let words = "Hangge.com" //不使用区间运算符 let index = words.index(words.startIndex, offsetBy: 4) let index2 = words.index(words.startIndex, offsetBy: 6) let range1 = Range(uncheckedBounds: (lower: index, upper: index2)) let rangeStr1 = words.substring(with: range1) //ge print(rangeStr1) //使用区间运算符 let range2 = words.index(words.startIndex, offsetBy:4)..<words.index(words.startIndex,offsetBy:6) let rangeStr2 = words.substring(with: range2) print(rangeStr2)
5,区间运算符除了返回一个Range外,还可以接受Comparable的输入,返回ClosedInterval或HalfOpenInterval
所以我们可以用这个特性检查字符串里的字符是不是都是合法字符(比如是不是都是小写)
let words = "Hangge.com" let interval = "a"..."z" for c in words.characters{ if !interval.contains(String(c)){ print("(c)不是小写字母") } }