设置字典

时间:2018-07-14 03:28:29

标签: swift dictionary set

我一直在尝试从Set创建一个[[Header: String]],但是还没有做到。

我尝试使用map(_:)flatMap(_:)Set,但是每当我使用Set时都会说:

  

无法推断出通用参数'Element'。

如何获取数组中的唯一记录?

enum Header: String, CustomStringConvertible {

    case name  = "name"
    case info  = "info"

    var description: String { return rawValue }
}


let dict: [[Header: String]] = [
    [.name: "John", .info: "100"],
    [.name: "Mary", .info: "120"],
    [.name: "Mark", .info: "100"],
    [.name: "Lisa", .info: "120"],
    [.name: "John", .info: "140"],
    [.name: "Mark", .info: "140"],
    [.name: "Lisa", .info: "100"],
    [.name: "Mary", .info: "140"],
    [.name: "Mark", .info: "140"],
    [.name: "Mary", .info: "120"]
]

1 个答案:

答案 0 :(得分:3)

您有Array个词典。 Dictionary不符合Hashable,因此它不能是集合的成员,也不能是另一个Dictionary中的键。

使用enum + Dictionary根本不适合您要建模的数据。相反,请使用结构:

struct Person: Hashable {
    let name: String
    let info: Int // TODO: Give me a better name
}

let people = [
    Person(name: "John", info: 100),
    Person(name: "Mary", info: 120),
    Person(name: "Mark", info: 100),
    Person(name: "Lisa", info: 120),
    Person(name: "John", info: 140),
    Person(name: "Mark", info: 140),
    Person(name: "Lisa", info: 100),
    Person(name: "Mary", info: 140),
    Person(name: "Mark", info: 140),
    Person(name: "Mary", info: 120),
]

let uniquePeople = Set(people)