Chaosed0
Chaosed0

Reputation: 969

Subscripting subdata obtained from range in Swift 4 results in EXC_BAD_INSTRUCTION

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.

Image of the crash

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

Answers (1)

Abdelahad Darwish
Abdelahad Darwish

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])

See image enter image description here

Upvotes: 3

Related Questions