首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在数组中搜索并删除文档?

如何在数组中搜索并删除文档?
EN

Stack Overflow用户
提问于 2019-10-27 11:51:26
回答 1查看 74关注 0票数 0

我正在尝试创建添加到收藏夹按钮,我可以将对象添加到数组中,但由于某些原因,我无法将其从数组中删除。如何将其从数组中删除?.Here是我的代码。谢谢

代码语言:javascript
运行
复制
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)])

  }
EN

回答 1

Stack Overflow用户

发布于 2019-10-27 15:16:07

你能试试这段代码吗:

代码语言:javascript
运行
复制
if let temp = user.favoritCar.first(where: {$0.id == item.id}) {
   if let index = user.favoritCar.firstindex(of: temp) {
      user.favoritCar.remove(at: index)
   }
}

而不是下面的代码:

代码语言:javascript
运行
复制
if user.favoritCar.contains(item.id!)  {
 let index = user.favoritCar.firstIndex(of:item.id!)
 user.favoritCar.remove(at: index!)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58576482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档