我一直在尝试从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"]
]
答案 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)