Để xóa một phần tử cụ thể khỏi Array trong Swift, có 2 cách chính: filter (tạo array mới) và remove(at:) (mutate array gốc).
Cách 1: filter(_:) - Tạo array mới (Functional, an toàn)
var array = ["a", "b", "c", "f"]
let filtered = array.filter { $0 != "f" }
print(filtered) // ["a", "b", "c"]
// array gốc không thay đổi

Cách 2: remove(at:) - Xóa tại index (Mutable, in-place)
var array = ["a", "b", "c", "f"]
if let index = array.firstIndex(of: "c") {
array.remove(at: index)
}
print(array) // ["a", "b", "f"]

Cách 3: removeAll(where:) - Swift 4.2+ (Mutating, lọc điều kiện)
var numbers = [1, 2, 6, 44, 6, 10]
numbers.removeAll { $0 == 6 }
print(numbers) // [1, 2, 44, 10] - xóa TẤT CẢ số 6
So sánh
| Phương pháp | Mutating? | Trả về | Xóa bao nhiêu? | Hiệu năng |
|---|---|---|---|---|
filter | Không | Array mới | Tất cả match | O(n), cấp phát mới |
remove(at:) | Có | Phần tử bị xóa | 1 (first index) | O(n) shift elements |
removeAll(where:) | Có | Void | Tất cả match | O(n), in-place |
Ví dụ với số
var nums = [1, 2, 6, 44]
let filtered = nums.filter { $0 != 6 } // [1, 2, 44]
print(filtered)
if nums.contains(1), let idx = nums.firstIndex(of: 1) {
nums.remove(at: idx)
}
print(nums) // [2, 6, 44]

Khuyến nghị
- Dùng
filterkhi muốn giữ array gốc, chain nhiều phép biến đổi. - Dùng
removeAll(where:)khi muốn xóa nhiều phần tử match condition trong array mutating. - Dùng
remove(at:)khi biết chính xác index hoặc chỉ xóa 1 phần tử đầu tiên tìm thấy. - Tránh
remove(at:)trong loop for-in (index shift) – dùngreversed()loop hoặcremoveAll(where:).