Reputation: 969
In Xcode 9.4, I have the following code in a Swift playground:
import Foundation
let data = Data([UInt8](arrayLiteral: 0x01, 0x02, 0x03, 0x04 ))
print (data[0])
let subdata = data.subdata(in: 2..<data.count)
print (subdata[0])
let subdataUsingIndex = data[2..<data.count]
print (subdataUsingIndex[0])
When this code runs, it crashes on the final line, where I try to subscript subadataUsingIndex
.
It is also happening in a non-playground project. Have I run into a language bug, or am I doing something wrong?
Upvotes: 4
Views: 2698
Reputation: 6067
Data.subdata Returns a new copy of the data in a specified range.
But the other one is data slice because data confirm to Collection Protocol
we can slice it on ranges Like array using subscribe syntax
let subdataUsingIndex = data[2..<data.count]
lower-bound
2 and upper-bound
is 4
let data = Data([UInt8](arrayLiteral: 0x01, 0x02, 0x03, 0x04 ))
print (data[0])
let subdata = data.subdata(in: 2..<data.count)
print (subdata[0])
let subdataUsingIndex = data[2..<data.count]
print (subdataUsingIndex[2])
Upvotes: 3