我正在使用Swift中的不同数据结构,我很想知道如何使用集合的remove at函数。documentation说该方法接受一个索引,我认为它应该是number,但是这不起作用。有人能告诉我使用这种方法的正确方法吗?
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)发布于 2018-08-22 10:57:49
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")发布于 2018-08-22 10:38:45
方法remove(at:)不接收整数,它接收Set<Element>.Index。您可以使用firstIndex(of:)来获取要删除的元素的索引。
https://stackoverflow.com/questions/51959079
复制相似问题