今天我遇到了一种情况,我正在使用可选的绑定对象数组作为可选项。
我在课程级别有一些对象&在一些函数调用我正在做可选绑定&从中删除项目。但是如果做了可选的可选biding然后从数组中删除了一个objet,那么原始数组仍然有该项。但是如果我从原始数组中删除那么项目将被删除。
extension WishlistController:WishlistActionDelegate {
func removedFromWishList(voucher: ShopVoucher) {
if var arrayWishlist = self.arrWishlist {
for (index,value) in arrayWishlist.enumerated() {
if value.id == voucher.id {
self.arrWishlist?.remove(at: index)
self.tableViewWishList.reloadData()
break
}
}
}
}
}
答案 0 :(得分:0)
数组是值类型,因此arrayWishList
和self.arrWishlist
是两个独立的实例,从一个项目中删除项目对另一个项目无效。
顺便说一句,这整件事可以简化为
self.arrWishlist = self.arrWishlist.filter({$0.id != voucher.id})
self.tableViewWishList.reloadData()
答案 1 :(得分:0)
尝试使用以下代码删除
这将删除数组中的第一个匹配ID并退出执行
var myArray : [String]?
myArray = ["item0","item1","item0","item1","item0","item1","item0","item1","item0","item1","item0","item1"]
let voucherID : String = "item1"
print("MyArray : \(myArray!)")
if (myArray?.contains(voucherID))!
{
let index : Int = (myArray?.index(of: voucherID))!
myArray?.remove(at: index)
}
print("After Removing:\(myArray!)")
控制台输出