首页 > 解决方案 > 如何使用 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)

标签: swiftset

解决方案


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")

推荐阅读