如何使用 Swift 显示数组的唯一元素? [英] How to display unique elements of an array using Swift?

查看:33
本文介绍了如何使用 Swift 显示数组的唯一元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重新调整数组的公式,例如var Array = [a,s,d,s,f,g,g,h,e].我想要的是运行 for 循环或其他一些选项,让我返回 a,s,d,f,g,h,e - 只有唯一值.我怎样才能用 ios Swift 做到这一点?

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?

推荐答案

如果你不在乎顺序:

只需使用一个集合:

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

如果您关心订单:

使用这个扩展,它允许你删除任何Sequence的重复元素,同时保持顺序:

If you care about the order:

Use this extension, which allows you to remove duplicate elements of any Sequence, 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"]

这篇关于如何使用 Swift 显示数组的唯一元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆