Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscripting subdata obtained from range in Swift 4 results in EXC_BAD_INSTRUCTION

Tags:

swift

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?

like image 236
Chaosed0 Avatar asked Oct 16 '25 15:10

Chaosed0


1 Answers

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

like image 181
Abdelahad Darwish Avatar answered Oct 18 '25 10:10

Abdelahad Darwish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!