nar0909
nar0909

Reputation: 135

"Fatal error: Index out of range" while working with byte array in swift 4?

I have the following code like this,

extension Collection {
func element(at index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}

class Example: UIViewController{
          ......

viewDidLoad(){..}
viewDidDisappear(){..}

func readandsend(){
let ReceiveData = rxCharacteristic?.value
        if let ReceiveData = ReceiveData {
            let ReceivedNoOfBytes = ReceiveData.count
            myByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
            (ReceiveData as NSData).getBytes(&myByteArray, length: ReceivedNoOfBytes)
            print("Data Received ",myByteArray)
               }

//Now I'm storing all my bytearray data here

var first = myByteArray[0]
var sec = myByteArray[1]
var third = myByteArray[2]
var fourth = myByteArray[3]

//Here I'm trying to get past out of range using extension block shown above

if let b1 = myByteArray.element(at: 0){
one = myByteArray[0]
}
if let b2 = myByteArray.element(at: 1){
two = myByteArray[1]
}
if let b3 = myByteArray.element(at: 2){
three = myByteArray[2]
}
if let b4 = myByteArray.element(at: 3){
four = myByteArray[3]
}

//I have two textbox's from which I need to get the strings and convert to UInt8

var tb1 = textbox1.text
var b1 = tb1.flatMap{UInt8(String($0))}

var tb2 = textbox2.text
var b2 = tb2.flatMap{UInt8(String($0))}

//Now when I try sending my completed byte array

 let completedArray = [UInt8]()

 completedArray[0] = b1
 completedArray[1] = b2
 completedArray[2] = myByteArray[2]
 completedArray[3] = myByteArray[3]

//Writing back to peripheral

let TransmitData = NSData(bytes: completedArray, length: completedArray.count)

peripheral.writeValue....so on

When I send it I'm getting an index out of range error, but have I properly used the extension block? Can someone pls help?

Upvotes: 1

Views: 1054

Answers (1)

jaket
jaket

Reputation: 9341

You need to either initialize the array with the necessary number of elements or append to the array.

Array Initialization:

let completedArray = [UInt8](count: 4)   
completedArray[0] = b1
...

Append:

let completedArray = [UInt8]()
completedArray.append(b1)
...

Upvotes: 2

Related Questions