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

1,闭区间运算符:a...b
1
2
3
for iCount in 512...1024{
     //从512遍历到1024(包括1024)
}

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
//字符串截取
let words = "Hangge.com"
 
//不使用区间运算符
let index = advance(words.startIndex, 4)
let index2 = advance(words.startIndex, 6)
var range1 = Range<String.Index>(start: index, end: index2)
var rangeStr1 = words.substringWithRange(range1) //ge
 
//使用区间运算符
var range2 = advance(words.startIndex, 4)..<advance(words.startIndex, 6)
var rangeStr2 = words.substringWithRange(range2) //ge

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

所以我们可以用这个特性检查字符串里的字符是不是都是合法字符(比如是不是都是小写)
1
2
3
4
5
6
7
8
9
10
11
let words = "Hangge.com"
        
let interval = "a"..."z"
for c in words {
    if !interval.contains(String(c)){
            println("\(c)不是小写字母")
    }
}
         
//H不是小写字母
//.不是小写字母
05-06 03:05