Swift新宠-区间运算符

2021-06-09  本文已影响0人  一个栗

闭区间运算符

for index in 1...5 {
    print("\(index) time 5 is \(index * 5)")
}

打印结果如下:
1 time 5 is 5
2 time 5 is 10
3 time 5 is 15
4 time 5 is 20
5 time 5 is 25

半开区间运算符

let names = ["zhangsan","lisi","wangwu","zhaoliu"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}

打印结果如下:
Person 1 is called zhangsan
Person 2 is called lisi
Person 3 is called wangwu
Person 4 is called zhaoliu

单侧区间

let names = ["zhangsan","lisi","wangwu","zhaoliu"]
let count = names.count

for name in names[2...] {
    print(name)
}
print("=======")
for name in names[...2] {
    print(name)
}
print("=======")
for name in names[..<2] {
    print(name)
}

打印结果如下:
wangwu
zhaoliu
=======
zhangsan
lisi
wangwu
=======
zhangsan
lisi

字符串索引区间

var welcome = "hello world"
let range = welcome.index(welcome.endIndex, offsetBy: -6) ..< welcome.endIndex
welcome.removeSubrange(range)
print(welcome)

打印结果如下:
hello

Comparable 区间

var welcome = "hello,world!"
let interval = "a" ... "z"
for c in welcome {
    if !interval.contains(String(c)) {
        print("\(c)不是小写字母")
    }
}

打印结果如下:
,不是小写字母
!不是小写字母

倒序

for i in (0...10).reversed() {
    print(i)
}

打印结果如下:
10
9
8
7
6
5
4
3
2
1
0
上一篇 下一篇

猜你喜欢

热点阅读