0

我在下面的方法中遇到了同时内存访问错误。谁能建议我应该如何修改它以消除此错误并保持功能完整。

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

这就是数组的定义方式var myItems : [String]?

任何建议表示赞赏。

4

1 回答 1

0

尝试更改var myItems : [String] = [String]()并在您的功能中进行适当的更改,如下所示

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)
        }
    }
于 2018-01-05T11:19:37.700 回答