Swift 5.x Set 定义、创建

2020-06-25  本文已影响0人  ShenYj

1. 创建Set

let letters = Set<Character>()
var letters: Set<String> = ["Math", "English", "History"]

注: 如果不指定类型为Set, 默认初始化的是数组

2. Set 类型的哈希值

e.g.

struct Person {
    var name: String = ""
    var age: Int = 0
}
var personSet = Set<Person>()  -->`Type 'Person' does not conform to protocol 'Hashable'`

注意此时在初始化这个Set的时候, 编译器会提示错误: Type 'Person' does not conform to protocol 'Hashable'

遵循Hashable协议后, 警告消失

struct Person: Hashable {
    var name: String = ""
    var age: Int = 0
}
var personSet = Set<Person>()

通过extension

struct Person {
    var name: String = ""
    var age: Int = 0
}
extension Person: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
        hasher.combine(age)
    }
}

var personSet = Set<Person>()
personSet.insert(Person(name: "zhangsan", age: 25))
personSet.insert(Person(name: "zhangsan", age: 25))
print(personSet)
上一篇下一篇

猜你喜欢

热点阅读