How to use Set to check for bool in Swift

Issue #725

When you want to check for existence using Bool, consider using Set over Dictionary with Bool, as Set guarantee uniqueness. If using Dictionary instead, the value for key is Optional<Bool> where we have to check for both optional and true false within.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Book: Hashable {
let id: UUID
let name: String
}

let book1 = Book(id: UUID(), name: "1")
let book2 = Book(id: UUID(), name: "2")

func useDictionary() {
var hasChecked: [Book: Bool] = [:]
hasChecked[book1] = true
print(hasChecked[book1] == Optional<Bool>(true))
print(hasChecked[book2] == Optional<Bool>.none)
}

func useSet() {
var hasChecked: Set<Book> = Set()
hasChecked.insert(book1)
print(hasChecked.contains(book1))
print(hasChecked.contains(book2))
}

Comments