I have been getting an array index out of range error and then came across this question.
And this is the block of code.
import UIKit
import Foundation
import CoreBluetooth
EDIT 1: From what Leo suggested, so the error is gone from this block but index out of range still persists
extension Collection where Index == Int {
func get(index: Int) -> Element? {
if 0 <= index && index < count {
return self[index]
} else {
return nil
}
}
}
class Sample:UIViewController{
.......
//This is where I'm sending data
func send(){
if let send1 = mybytes.get(index: 2){
byteat2 = bytefromtextbox
print(byteat2)
}
}
}
But it doesn't seem to work.
I get an error at return self[index]
in extension Collection{}
I have also tried the following,
byteat2.insert(bytefromtextbox!, at:2)
But it returns an index out of range error.
Can someone help/advice a solution?
You should use
append
instead ofinsert
and just use array subscript instead of creating a get method. You just need check the array count before trying to access the value at the index or even better approach would be checking if the collection indices contains the index:If you really want to implement a get method add a constraint to the index
extension Collection where Index == Int
or change your index parameter fromInt
toIndex
: