【问题标题】:how to search for document in an array and delete it?如何在数组中搜索文档并将其删除?
【发布时间】:2019-10-27 03:51:25
【问题描述】:

我正在尝试创建添加到收藏按钮,我能够将对象添加到数组中,但由于某种原因我无法从数组中删除它。如何从数组中删除它? .这是我的代码。谢谢

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

  }

【问题讨论】:

    标签: ios swift google-cloud-firestore firestorter


    【解决方案1】:

    你能试试这个代码吗:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2021-11-28
      • 1970-01-01
      • 2012-08-16
      • 2011-10-08
      • 2023-04-08
      • 2013-03-04
      相关资源
      最近更新 更多