Bỏ qua để đến nội dung

Set

Set là collection chứa các giá trị duy nhất, không có thứ tự.

// 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>()
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
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
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]
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
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) }
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]
// 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()
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

  • 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