Skip to Content

Set trong Swift

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

// Với type annotation var numbers: Set<Int> = [1, 2, 3, 4, 5] // Type inference var fruits: Set = ["apple", "banana", "cherry"] // Set rỗng var empty = Set<String>()

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 tra print(set.contains(3)) // true print(set.count) // 3 print(set.isEmpty) // false

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 được print(numbers.count) // 3

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 Difference print(a.symmetricDifference(b)) // [1, 2, 5, 6]

6. So sánh Sets

let a: Set = [1, 2, 3] let b: Set = [1, 2, 3, 4, 5] // Subset/Superset print(a.isSubset(of: b)) // true print(b.isSuperset(of: a)) // true // Disjoint (không có phần tử chung) let c: Set = [6, 7, 8] print(a.isDisjoint(with: c)) // true

7. Duyệt Set

let fruits: Set = ["apple", "banana", "cherry"] // for-in for fruit in fruits { print(fruit) } // Sorted iteration for fruit in fruits.sorted() { print(fruit) } // forEach fruits.forEach { print($0) }

8. Filter và Map

let numbers: Set = [1, 2, 3, 4, 5, 6] // filter let evens = numbers.filter { $0 % 2 == 0 } print(evens) // [2, 4, 6] // map trả về Array let doubled = numbers.map { $0 * 2 } print(doubled) // [2, 4, 6, 8, 10, 12]

9. Chuyển đổi

// Array -> Set let array = [1, 2, 2, 3, 3, 3] let set = Set(array) print(set) // [1, 2, 3] // Set -> Array let backToArray = Array(set) // Set -> Sorted Array let sortedArray = set.sorted()

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êm print(people.count) // 2

📝 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
Last updated on