访问 Set
- 可以使用 For - In 遍历 Set
- 因为Set 是无序的,如果要顺序遍历 Set,使用 sorted() 方法
let courses:Set = ["Math", "English", "History"]
for course in courses {
print(course)
}
print("------")
for course in courses.sorted() {
print(course)
}
执行结果如下:
History
Math
English
------
English
History
Math
- 使用 count 获取 Set 元素个数
- 使用 isEmpty 判断 Set 是否为空
let set:Set<Character> = ["A", "B", "C"]
print(set.count)
print(set.isEmpty)
执行结果如下:
3
false
添加元素
- insert(_:) 添加一个元素到 Set
- update(with:) 如果已经有相等的元素,替换为新元素。如果Set 中没有,则插入
struct Person {
var name : String
var age: Int
}
extension Person: Hashable {
func hash(into hasher:inout Hasher) {
hasher.combine(name)
}
}
extension Person:Equatable {
static func == (lhs:Person, rhs:Person) -> Bool {
return lhs.name == rhs.name
}
}
var personSet:Set = [Person(name: "zhangsan", age: 20)]
personSet.update(with: Person(name: "zhangsan", age: 20))
personSet.update(with: Person.init(name: "wangwu", age: 15))
print(personSet)
执行结果如下:
[__lldb_expr_7.Person(name: "wangwu", age: 15), __lldb_expr_7.Person(name: "zhangsan", age: 20)]
移除元素
- filter(_:) 返回一个新的Set,新Set 的元素是原始Set 符合条件的元素
var personSet:Set = [Person(name: "zhangsan", age: 28), Person(name: "lisi", age: 29)]
personSet.update(with: Person(name: "zhangsan", age: 38))
personSet.update(with: Person(name: "wangwu", age: 18))
print(personSet.filter{$0.age > 20})
执行结果如下:
[__lldb_expr_12.Person(name: "lisi", age: 29), __lldb_expr_12.Person(name: "zhangsan", age: 38)]
- remove(_:) 从 Set 当中移除一个元素,如果元素是 Set 的成员就移除它,并且返回移除的值,如果集合每天这个成员,就返回nil
- removeAll() 移除所有元素
var personSet:Set = [Person(name: "zhangsan", age: 28), Person(name: "lisi", age: 29)]
personSet.update(with: Person(name: "zhangsan", age: 38))
personSet.update(with: Person(name: "wangwu", age: 18))
personSet.remove(Person(name: "zhangsan", age:33))
print(personSet)
执行结果如下:
[__lldb_expr_14.Person(name: "lisi", age: 29), __lldb_expr_14.Person(name: "wangwu", age: 18)]
- removeFirst() 移除 Set 的第一个元素,因为 Set 是无序的,所以第一个元素并不是放入的第一个元素,而是哈希排布之后的第一个元素。
var personSet:Set = [Person(name: "zhangsan", age: 28), Person(name: "lisi", age: 29)]
personSet.update(with: Person(name: "zhangsan", age: 38))
personSet.update(with: Person(name: "wangwu", age: 18))
personSet.removeFirst()
print(personSet)
执行结果如下:
[__lldb_expr_16.Person(name: "zhangsan", age: 38), __lldb_expr_16.Person(name: "lisi", age: 29)]
网友评论