swift - 如何使用 Swift set remove at 方法?
问题描述
我在 Swift 中使用不同的数据结构,我很想知道如何为 Set 使用 remove at 函数。文档说该方法接受一个索引,虽然我会在其中编号,但这不起作用。有人可以告诉我使用这种方法的正确方法吗?
var girlfriends: Set = ["Karlie", "Francis", "Mya", "Zoe", "Daisy", "Bambi"]
print(girlfriends)
for _ in 1...10 {
print(girlfriends)
}
girlfriends.insert("Joyce")
print(girlfriends)
girlfriends.insert("Bambi")
print(girlfriends)
girlfriends.insert("Vicki")
print(girlfriends)
// doesn't compile var beach = girlfriends["Vicki"]
// doesn't compile girlfriends.remove(at: 2)
解决方案
Set 操作中的最后两行具有不同的方法来获取和删除值。下面描述了如何实现这一点。
//To get the value
if let beach = girlfriends.first(where: { $0 == "Vicki" }) {
print(beach) //here you will get the value
}
//To remove it at certain index, which is different then Int index like on array
if let indexToRemove = girlfriends.index(of: "Vicki") {
girlfriends.remove(at: indexToRemove)
}
//OR
girlfriends.remove("Vicki")
推荐阅读
- c# - 在保持默认值的同时使文本消失
- c - 将字符与指针用于“单词数组”
- ruby-on-rails - 使用 CSRF 通过 Curl 将删除发送到 Rails 后端
- javascript - 按下 Tab 键时将表格内容变为可编辑
- karate - 断言错误 - 无法将 java.lang.String 转换为 java.util.List
- node.js - 条带连接创建客户的正确电话号码格式
- highcharts - 在 Highcharts 中隐藏线段
- javascript - 传单:如何否决打开覆盖层?
- python - ModuleNotFoundError:没有名为 ERROR 的模块
- python - 如何使用while循环获取输出?