在Swift对象数组中收集多个唯一属性值

时间:2016-06-05 15:53:20

标签: swift functional-programming

说我有一个简单的Ingredient类:

class Ingredient {
    let section : String // 'Produce', 'Spices', 'Dairy', 'Grains'
}

我有一堆Ingredient件物品:

var ingredients : [Ingredient] = ...

我想从这些成分中收集数量不同的部分

我可以通过Java(依赖于Set类型的自动聚集)来实现这一点:

ingredients.stream().map(Ingredient::getSection).collect(Collectors.toSet()).count()

或者,使用distinct()方法:

ingredients.stream().map(Ingredient::getSection).distinct().count()

但是我正在寻找在Swift中做类似单行的方法。我所做的一些研究表明人们编写自己的方法来收集不同的值,但我希望有一个distinct()Set - 收集Swift类型的方法。

4 个答案:

答案 0 :(得分:7)

当然,您可以通过映射您的配料数组以提取一系列部分来以相同的方式执行此操作 - 然后您可以将这些转换为extension CollectionType where Generator.Element : Hashable { func distinct() -> [Generator.Element] { return Array(Set(self)) } } let sections = ingredients.map{ $0.section }.distinct() 并计算出数量,并为您提供数量不同的部分。

Set

答案 1 :(得分:3)

大多数情况一样,您应该使用{ "presets": ["es2015", "react"] } 类型:

Set

此外,没有什么比声明自己的let ingredients = [Ingredient(section: "Produce"), Ingredient(section: "Produce"), Ingredient(section: "Spices"), Ingredient(section: "Dairy")] let sections = Set(ingredients.map{ $0.section }) let numDistinctSections = Set(ingredients.map{ $0.section }).count 函数更简单了:

distinct

答案 2 :(得分:2)

不确定。将您的部分变为<script type="text/javascript" src="popup.js"></script>,使用它创建</body>并获取如下计数:

[String]

答案 3 :(得分:1)

使用Swift 3,并保持O(n)的复杂性,它看起来像这样:

extension Array where Element: Hashable {

    func distinct() -> Array<Element> {
        return Array(Set(self))
    }
}
相关问题