【问题标题】:Swift remove item in array快速删除数组中的项目
【发布时间】:2016-08-05 06:34:29
【问题描述】:

我对 SwityJson 和删除数组元素有疑问

为了进一步处理数据,我必须删除一些元素。

这是我的代码

self.jsonObj = JSON(value)

//Filtern 

for i in 0 ..< self.jsonObj["customer"].count {

    if self.jsonObj["customer"][i]["Group_A"].string == "Mr Abcde" 
            || self.jsonObj["customer"][i]["Group_A"].string == "Mr Bcde" 
            || self.jsonObj["custome"][i]["Group_B"].string == "Mr Abcde" 
            || self.jsonObj["customer"][i]["Group_B"].string == "Mr Bcde" 
    {
        self.jsonObj["customer"].arrayObject?.removeAtIndex(i)
    }
}

现在的问题:如果运行代码,并非所有找到的元素都被删除。 我认为循环遍历所有元素太快了。删除任务没有时间?! 我该如何处理。循环中...找到了一些东西...停止循环...删除项目...开始循环..

通过创建三次 If 语句,一切都很好,所有找到的元素都被删除,但是,这不是我想要的。

或者是否可以过滤数组然后说

filterdData = jsonObj

【问题讨论】:

    标签: arrays swift swifty-json


    【解决方案1】:

    试试

                //Filtern 
    
     for i in 0 ..< self.jsonObj["customer"].count {
          let groupA = self.jsonObj["customer"][i]["Group_A"].string
          let groupB = self.jsonObj["customer"][i]["Group_B"].string
    
                if  groupA == "Mr Abcde" || groupA == "Mr Bcde" || groupB == "Mr Abcde" || groupB == "Mr Bcde"{
                        self.jsonObj["customer"].rawArray.removeAtIndex(i)
                }                   
     }
    

    这不仅减少了对 JSON 对象的调用(可能会节省速度),而且它还使用 rawArray 而不是 arrayObject 直接写入数组而不是通过 arrayObject 到 rawArray。

    【讨论】:

    • 对不起,结果是一样的..:( 不是所有找到的元素都被删除了
    【解决方案2】:

    问题是您正在更改从循环内终止循环的计数。您不需要这样做,也许使用过滤器或相关方法来代替

    【讨论】:

      【解决方案3】:

      我建议在修改数据之前对其进行规范化。但如果失败了,你可以试试这个:

      let filteredJson = self.jsonObj["customer"].filter { elem  in
        !(["Mr Abcde", "Mr Bcde"].contains(elem.["Group_A"].string) ||
          ["Mr Abcde", "Mr Bcde"].contains(elem.["Group_B"].string))
      }
      

      然后使用filteredJson 常量。

      【讨论】:

      • 好主意,但是如何将filteredJson 转换为JSON 格式??
      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2017-07-11
      • 2013-01-17
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多