Swift中的区间类型对应着OC的NSRange类型,那么Swift中的区间类型是怎么使用的呢?
Swift中的区间简单介绍.png下面是了解区间类型的demo
1. 认识区间类型
func testRange() {
let range1: ClosedRange<Int> = 1...4
let range2: Range<Int> = 4..<7
let range3: PartialRangeThrough<Int> = ...9
let range4: PartialRangeFrom = 9...
let range5: PartialRangeUpTo = ..<18
}
2. Range在Sring使用中的例子
func testRangeInString() {
let str = "123456789"
let index1 = String.Index(utf16Offset: 1, in: str)
let index5 = String.Index(utf16Offset: 5, in: str)
let index7 = String.Index(utf16Offset: 7, in: str)
let range1: ClosedRange = index1 ... index5
let range2: Range = index5 ..< index7
let range3: PartialRangeThrough = ...index5
let range4: PartialRangeFrom = index1...
let range5: PartialRangeUpTo = ..<index7
print(str[range1])
print(str[range2])
print(str[range3])
print(str[range4])
print(str[range5])
// 打印结果:
/*
23456
67
123456
23456789
1234567
*/
}
3. Range在数组中使用的例子
func testRangeInArray() {
testRangeWithOC()
let arr = [1, 2, 3, 4, 5, 6, 7]
print("闭区间取数组元素\(arr[1...3])")
print("半闭区间取数组元素\(arr[1..<3])")
print("左开右闭区间取数组元素\(arr[...3])")
print("左开右半闭区间取数组元素\(arr[..<3])")
print("左闭右开区间取数组元素\(arr[1...])")
// 打印结果:
/*
闭区间取数组元素[2, 3, 4]
半闭区间取数组元素[2, 3]
左开右闭区间取数组元素[1, 2, 3, 4]
左开右半闭区间取数组元素[1, 2, 3]
左闭右开区间取数组元素[2, 3, 4, 5, 6, 7]
*/
}
4. Range与NSRange的相互转换
func testRangeWithOC() {
print("OC与Swift的range混编----")
let ocRange = NSMakeRange(1, 3)
print("ocRange:\(ocRange)")// ocRange:{1, 3}
print("ocRange转半闭区间----")
guard let range = Range(ocRange) else {
return
}
range.forEach({ num in
print(num)
})// 1 2 3
print(range) // 1..<4
let ocRange2 = NSMakeRange(range.lowerBound, range.count)
print(ocRange2)// {1, 3}
// 以下会报错
// let range1 = ClosedRange<Int>(ocRange)
// let range2 = PartialRangeThrough<Int>(ocRange)
// let range3 = PartialRangeUpTo<Int>(ocRange)
// let range4 = PartialRangeFrom<Int>(ocRange)
}
网友评论