Article directory
1. Several methods of intercepting strings
1. Intercept the first few characters
mobileID.prefix(32)
2. Intercept the last few digits
mobileID.suffix(3)
3. subData
data.subdata(in: 0..<4)
4. Subscript interception
data[0..<4]
2. subData(in:) reports error EXC_BREAKPOINT
Reason: Indexes of Data values (or collections in general) are not necessarily zero-based.
Here is a piece of code
let array:[UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]
let data = Data(bytes: array)
//问题:请问以下六个的结果是?
data.subdata(in: 3...4).forEach{ print("a \($0)") }
data.subdata(in: 3..<3).forEach{ print("b \($0)") }
data.subdata(in: 3..<4).forEach{ print("c \($0)") }
data[3...4].forEach{ print("A \($0)") }
data[3..<3].forEach{ print("B \($0)") }
data[3..<4].forEach{ print("C \($0)") }
result:
data.subdata(in: 3...4).forEach{ print("a \($0)") }// 报错 Cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<Data.Index>' (aka 'Range<Int>')
data.subdata(in: 3..<3).forEach{ print("b \($0)") }// 空值
data.subdata(in: 3..<4).forEach{ print("c \($0)") }// c 4
data[3...4].forEach{ print("A \($0)") }// A 4 A 5
data[3..<3].forEach{ print("B \($0)") }// 空
data[3..<4].forEach{ print("C \($0)") }// C 4
data.subdata(in: 3…4) Reason for error:
The value passed by this method is Range<Data.Index> (Data.Index is actually Int)
And 3…4 is actually ClosedRange
We know that after Swift 3.0, there are four types of Range:
These four Ranges cannot be directly converted between each other
, so data.subdata(in: 3…4) will report the above error.
Why can both CountableClosedRange and CountableRange be used for subscript values?
Looking through the Swift source code, you will know the reason.
Swift defines subscript values for four Ranges.