Set
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”Set là collection chứa các giá trị duy nhất, không có thứ tự.
2. Tạo Set
Phần tiêu đề “2. Tạo Set”// Với type annotationvar numbers: Set<Int> = [1, 2, 3, 4, 5]
// Type inferencevar fruits: Set = ["apple", "banana", "cherry"]
// Set rỗngvar empty = Set<String>()3. Các thao tác cơ bản
Phần tiêu đề “3. Các thao tác cơ bản”var set: Set = [1, 2, 3]
// Thêm phần tửset.insert(4)
// Xóa phần tửset.remove(2)
// Kiểm traprint(set.contains(3)) // trueprint(set.count) // 3print(set.isEmpty) // false4. Tính chất duy nhất
Phần tiêu đề “4. Tính chất duy nhất”var numbers: Set = [1, 2, 2, 3, 3, 3]print(numbers) // [1, 2, 3]
numbers.insert(2) // Không thêm đượcprint(numbers.count) // 35. Phép toán tập hợp
Phần tiêu đề “5. Phép toán tập hợp”let a: Set = [1, 2, 3, 4]let b: Set = [3, 4, 5, 6]
// Hợp (Union)print(a.union(b)) // [1, 2, 3, 4, 5, 6]
// Giao (Intersection)print(a.intersection(b)) // [3, 4]
// Hiệu (Difference)print(a.subtracting(b)) // [1, 2]
// Symmetric Differenceprint(a.symmetricDifference(b)) // [1, 2, 5, 6]6. So sánh Sets
Phần tiêu đề “6. So sánh Sets”let a: Set = [1, 2, 3]let b: Set = [1, 2, 3, 4, 5]
// Subset/Supersetprint(a.isSubset(of: b)) // trueprint(b.isSuperset(of: a)) // true
// Disjoint (không có phần tử chung)let c: Set = [6, 7, 8]print(a.isDisjoint(with: c)) // true7. Duyệt Set
Phần tiêu đề “7. Duyệt Set”let fruits: Set = ["apple", "banana", "cherry"]
// for-infor fruit in fruits { print(fruit)}
// Sorted iterationfor fruit in fruits.sorted() { print(fruit)}
// forEachfruits.forEach { print($0) }8. Filter và Map
Phần tiêu đề “8. Filter và Map”let numbers: Set = [1, 2, 3, 4, 5, 6]
// filterlet evens = numbers.filter { $0 % 2 == 0 }print(evens) // [2, 4, 6]
// map trả về Arraylet doubled = numbers.map { $0 * 2 }print(doubled) // [2, 4, 6, 8, 10, 12]9. Chuyển đổi
Phần tiêu đề “9. Chuyển đổi”// Array -> Setlet array = [1, 2, 2, 3, 3, 3]let set = Set(array)print(set) // [1, 2, 3]
// Set -> Arraylet backToArray = Array(set)
// Set -> Sorted Arraylet sortedArray = set.sorted()10. Set với Custom Types
Phần tiêu đề “10. Set với Custom Types”struct Person: Hashable { let name: String let age: Int}
var people: Set<Person> = [ Person(name: "Alice", age: 25), Person(name: "Bob", age: 30)]
people.insert(Person(name: "Alice", age: 25)) // Không thêmprint(people.count) // 2📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”- Set chứa các phần tử duy nhất
- Không đảm bảo thứ tự
- union, intersection, subtracting
- isSubset, isSuperset, isDisjoint
- Phần tử phải conform Hashable
- Chuyển Array -> Set để loại trùng