gpt4 book ai didi

arrays - 正确从数组中删除数据

转载 作者:行者123 更新时间:2023-11-30 12:11:21 24 4
gpt4 key购买 nike

我面临的问题是,我用数据填充了一个数组,当我稍后想删除它时,即使我调用 removeAll() ,数组仍然不为空。

更好地查看我的代码,以便更清楚地了解问题

更新了新代码

  @objc func textFieldDidChange() {

doSearch()

if let commentText = commentTextField.text , !commentText.isEmpty {
sendButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
sendButton.isEnabled = true
return
}

sendButton.setTitleColor(UIColor.lightGray, for: UIControlState.normal)
sendButton.isEnabled = false
}


func doSearch() {
let caption = commentTextField.text

let words = caption?.components(separatedBy: CharacterSet.whitespacesAndNewlines)

self.usersSuggestion.removeAll()


for var word in words! {
self.usersSuggestion.removeAll()


if word.hasPrefix("@") {
word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters)
self.isCellSelected = true
self.usersSuggestion.removeAll()
API.User.suggestUsers(withText: word, completion: { (user) in
print("closure", word)


self.usersSuggestion.append(user)
self.tableView.reloadData()

print("@", self.usersSuggestion.count)

})

self.usersSuggestion.removeAll()
tableView.reloadData()


} else {
self.isCellSelected = false
self.usersSuggestion.removeAll()
tableView.reloadData()

}
self.usersSuggestion.removeAll()
tableView.reloadData()
}



}

我在这里面临的问题是,即使我多次调用removeAll()方法,数组也永远不会回到0。当我有2个用户时,链接一个,下次我写一个@时我会得到2个用户+链接的用户(所以他两次)。我可以无限地做到这一点,只需 2 个现有用户即可拥有大约 100 个 userSuggestions。

照片

enter image description here

enter image description here

最佳答案

您在数组中插入元素后立即打印计数。这将始终给出 1 的计数。

                                       // count was zero
self.hashTags.insert(hashTag, at: 0) // adding one
print("# = ", self.hashTags.count) // count is now 1

鉴于 API.user... 函数使用完成处理程序,我假设这发生在单独的线程中或至少异步发生,因此您可能会遇到 UI 显示为空并突然显示为空的情况。

您可能希望以不同的方式构建代码,以更好地区分请求数据和显示(异步获取的)结果。嵌入式完成处理程序往往会产生误导,并给人留下执行将按照其视觉组织顺序发生的印象。

关于arrays - 正确从数组中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46013965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com