Simultaneous memory access error while inserting element in array

55 Views Asked by At

I'm getting Simultaneous memory access error in my below method. Can anyone advice how should I modify it to remove this error and keep the functionality intact.

func add(myItem:String, atIndex index:Int){

    if self.myItems!.count-1 > index {
        self.myItems?.insert(myItem, at: index)
    }
    else{

        while index > self.myItems!.count {
            //getting error in this insert statement below
            self.myItems?.insert(myItemPlaceHolder, at: self.myItems!.count)
        }

        self.myItems?.append(myItem)
    }
}

This is how the array is defined var myItems : [String]?

Any advice is appreciated.

1

There are 1 best solutions below

0
On

Try changing var myItems : [String] = [String]() and make appropriate changes in your function like below

func add(myItem:String, atIndex index:Int){

        if self.myItems.count-1 > index {
            self.myItems.insert(myItem, at: index)
        }
        else{

            while index > self.myItems.count {
                self.myItems.insert(myItemPlaceHolder, at: self.myItems.count)
            }

            self.myItems.append(myItem)
        }
    }