在swift中为数组附加唯一值

Gui*_*uce 12 arrays append swift

我在Swift上没有找到任何东西.找到了如何在数组上找到唯一值,但不是这样.对不起,如果听起来很基本......

但我有以下数组

var selectedValues = [String]()
Run Code Online (Sandbox Code Playgroud)

以及来自Parse查询的以下值

 var objectToAppend = object.objectForKey("description")! as! String
Run Code Online (Sandbox Code Playgroud)

这就是我现在这样做的方式.

self.selectedHobbies.append(objectToAppend)
Run Code Online (Sandbox Code Playgroud)

但由于查询重复发生,最终会附加重复值.它有效,但我只是想浪费内存,只保留独特的价值观.

关于如何在swift中解决这个问题的任何想法?

Mun*_*ndi 17

您可以使用Set保证唯一值的a.

var selectedValues = Set<String>()
// ...
selectedValues.insert(newString) // will do nothing if value exists
Run Code Online (Sandbox Code Playgroud)

当然,a的元素Set不是有序的.

如果您想保留订单,Array请在插入之前继续进行但是检查.

if !selectedValues.contains("Bar") { selectedValues.append("Bar") }
Run Code Online (Sandbox Code Playgroud)


BEN*_*oud 5

我想你的问题已经解决了,但我为下一个面临同样问题的开发人员添加了我的答案:)

我的解决方案是编写 Array 的扩展,以一种独特的方式从数组中添加元素:

这里的代码:

extension Array{
    public mutating func appendDistinct<S>(contentsOf newElements: S, where condition:@escaping (Element, Element) -> Bool) where S : Sequence, Element == S.Element {
      newElements.forEach { (item) in
        if !(self.contains(where: { (selfItem) -> Bool in
            return !condition(selfItem, item)
        })) {
            self.append(item)
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

例子:

var accounts: [Account]
let arrayToAppend: [Account]
accounts.appendDistinct(contentsOf: arrayToAppend, where: { (account1, account2) -> Bool in
        return account1.number != account2.number
})
Run Code Online (Sandbox Code Playgroud)