Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách xóa phần tử cụ thể khỏi Array trong Swift

Để 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 xóa phần tử cụ thể khỏi Array trong Swift

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 xóa phần tử cụ thể khỏi Array trong Swift

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ápMutating?Trả vềXóa bao nhiêu?Hiệu năng
filterKhôngArray mớiTất cả matchO(n), cấp phát mới
remove(at:)CóPhần tử bị xóa1 (first index)O(n) shift elements
removeAll(where:)CóVoidTất cả matchO(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]

Cách xóa phần tử cụ thể khỏi Array trong Swift

Khuyến nghị

  • Dùng filter khi 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ùng reversed() loop hoặc removeAll(where:).