swift中数组的唯一值 [英] Unique values of array in swift

查看:91
本文介绍了swift中数组的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用swift构建一个iOS应用程序,我需要获得字符串数组的所有唯一值。

I'm building an iOS app with swift and i need to get all unique values of array of strings.

我一直在阅读苹果开发人员文档但是它似乎没有它的功能。

I've been reading the apple developer docs but it doesn't seem to have a function for it.

有人可以给我一个提示吗?

Can someone give me an hint?

推荐答案

一种方法是使用一套:

let array = ["one", "one", "two", "two", "three", "three"]
let unique = Array(Set(array))
// ["one", "two", "three"]

您还可以创建一个更明确地过滤数组的扩展名:

You could also create an extension that filters through the array more explicitly:

extension Array where Element : Equatable {
    var unique: [Element] {
        var uniqueValues: [Element] = []
        forEach { item in
            if !uniqueValues.contains(item) {
                uniqueValues += [item]
            }
        }
        return uniqueValues
    }
}

注意

唯一数组将以未指定的顺序排列,您可能需要对其进行排序。有时最好通过枚举来自己做,你可以写一个扩展名。

The unique array will be in an unspecified order, and you may need to sort it. Sometimes it's better to just do it yourself by enumerating, you could write an extension.

进行扩展可能会很好(Swift 2):

It might be good to make an extension (Swift 2):

extension Array where Element : Hashable {
    var unique: [Element] {
        return Array(Set(self))
    }
}

可能有更多优化的方法可以做你想要的,但这种方式既快捷又简单。

There are probably more optimized ways to do what you want, but this way is quick and easy.

这篇关于swift中数组的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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