我正在尝试创建添加到收藏夹按钮,我可以将对象添加到数组中,但由于某些原因,我无法将其从数组中删除。如何将其从数组中删除?.Here是我的代码。谢谢
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)])
}
发布于 2019-10-27 07:16:07
你能试试这段代码吗:
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!)
https://stackoverflow.com/questions/58576482
复制相似问题