我试图创建“添加到收藏夹”按钮,我能够将对象添加到数组中,但是由于某些原因,我无法从数组中删除它。如何从阵列中删除它?这是我的代码。谢谢
func didClickFavoriteButton(item: Item) {
// removing from favorite (not working)
if user.favoritCar.contains(item.id!) {
let index = user.favoritCar.firstIndex(of:item.id!)
user.favoritCar.remove(at: index!)
FirebaseReference(.User).document(kFAVORIT).updateData([kFAVORIT :
FieldValue.arrayRemove(user.favoritCar)])
} else {
// Adding to favorite
user.favoritCar.append(item.id!)
FirebaseReference(.User).document(Auth.auth().currentUser!.uid).updateData([kFAVORIT : FieldValue.arrayUnion(user.favoritCar)])
}
答案 0 :(得分:0)
您可以尝试以下代码吗?
if let temp = user.favoritCar.first(where: {$0.id == item.id}) {
if let index = user.favoritCar.firstindex(of: temp) {
user.favoritCar.remove(at: index)
}
}
代替此代码:
if user.favoritCar.contains(item.id!) {
let index = user.favoritCar.firstIndex(of:item.id!)
user.favoritCar.remove(at: index!)