How to display unique elements of an array using Swift? [duplicate]

末鹿安然 提交于 2019-11-27 07:47:49

问题


This question already has an answer here:

  • Removing duplicate elements from an array in Swift 41 answers
  • Swift 3 Generics: How to Find The Common Set of Two Generic Arrays 2 answers

I have a formula retuning an array as example var Array = [a,s,d,s,f,g,g,h,e]. What I want is to run a for loop or some other option that gives me back a,s,d,f,g,h,e - only the unique values. How can I do this with ios Swift?


回答1:


If you don't care about order:

Simply use a set:

let set: Set = ["a", "s", "d", "s", "f", "g" , "g", "h", "e"]
print(set) // ["a", "s", "f", "g", "e", "d", "h"]

If you care about the order:

Use this extension, which allows you to remove duplicate elements of AnySequence, while preserving order:

extension Sequence where Iterator.Element: Hashable {
    func unique() -> [Iterator.Element] {
        var alreadyAdded = Set<Iterator.Element>()
        return self.filter { alreadyAdded.insert($0).inserted }
    }
}

let array = ["a", "s", "d", "s", "f", "g" , "g", "h", "e"]
let result = array.unique()
print(result) // ["a", "s", "d", "f", "g", "h", "e"]


来源:https://stackoverflow.com/questions/40579554/how-to-display-unique-elements-of-an-array-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!