首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Swift set remove at方法?

如何使用Swift set remove at方法?
EN

Stack Overflow用户
提问于 2018-08-22 10:25:00
回答 2查看 2.3K关注 0票数 1

我正在使用Swift中的不同数据结构,我很想知道如何使用集合的remove at函数。documentation说该方法接受一个索引,我认为它应该是number,但是这不起作用。有人能告诉我使用这种方法的正确方法吗?

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-22 10:57:49

Set操作中的最后两行具有不同的获取和删除值的方法。下面描述了如何实现这一点。

代码语言:javascript
复制
//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")
票数 2
EN

Stack Overflow用户

发布于 2018-08-22 10:38:45

方法remove(at:)不接收整数,它接收Set<Element>.Index。您可以使用firstIndex(of:)来获取要删除的元素的索引。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51959079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档