最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

[已解决]Swift中如何实现在循环中删除元素

Swift crifan 113浏览 0评论

用代码:

        let indexPathToDelList:[(Int, Int)] = [(Int, Int)]()
       
for (sectionIdx, eachSection) in contactSectionItemList.enumerate() {
           
if !(isFixedTopSection(eachSection)) {
               
for (idxInSection, eachContactItem) in eachSection.contactItemList.enumerate() {
                   
if eachContactItem.type == ContactType.TeamColleague {
                       
contactSectionItemList[sectionIdx].contactItemList.removeAtIndex(idxInSection)
                       
print("contactSectionItemList[sectionIdx]=\(contactSectionItemList[sectionIdx])")
                    }
                }
            }
        }

执行时出错:

需要去研究出一种办法:

如何实现在循环中,删除对应的元素

swift delete during loop

swift delete during enumeration

ios – Removing from array during enumeration in Swift? – Stack Overflow

Selectively remove and delete objects from a NSMutableArray in Swift – Stack Overflow

objective c – Best way to remove from NSMutableArray while iterating? – Stack Overflow

【总结】

所以有两种方案:

倒序

把要删除掉都加入到一个数组,最后一次性删除即可。

但是后者方案,不适合我此处:

我此处不是一个纯粹的数组,是个复合型的数组。

所以还是用第一种方案。

    func removeTeamColleagueContactItems() {
       
for var sectionIdx = contactSectionItemList.count 1; sectionIdx >= 0 ; –sectionIdx {
           
if !(isFixedTopSection(contactSectionItemList[sectionIdx])) {
               
for var contactIdxInSection = contactSectionItemList[sectionIdx].contactItemList.count 1; contactIdxInSection >= 0 ; –contactIdxInSection {
                   
if contactSectionItemList[sectionIdx].contactItemList[contactIdxInSection].type == ContactType.TeamColleague {
                       
//print("deleted team colleague [\(sectionIdx) – \(contactIdxInSection)]=\(contactSectionItemList[sectionIdx].contactItemList[contactIdxInSection])")
                        contactSectionItemList[sectionIdx].contactItemList.removeAtIndex(contactIdxInSection)
                    }
                }
               
               
//remove empty section
                if contactSectionItemList[sectionIdx].contactItemList.count == 0 {
                   
//print("delete empty section \(sectionIdx) =\(contactSectionItemList[sectionIdx].indexTitleStr)")
                    contactSectionItemList.removeAtIndex(sectionIdx)
                }
            }
        }
    }

即可实现:

倒序循环去删除对应的某个section中的某个元素item

删除完毕某个section后,如果发现为空,再去删除section

转载请注明:在路上 » [已解决]Swift中如何实现在循环中删除元素

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
18 queries in 0.287 seconds, using 9.76MB memory