Archive/잡동사니

Swift remove element from array by value

lgvv 2021. 11. 17. 01:39

Swift remove element from array by value

 

 

var array = [1, 2, 3]
array.remove(at: 0) // array is now [2, 3]

 

 

var array = ["hello", "world"]
if let index = array.firstIndex(of: "hello") {
  array.remove(at: index) // array is now ["world"]
}

 

 

var array = ["hello", "world", "hello"]
if let index = array.firstIndex(of: "hello") {
  array.remove(at: index) // array is now ["world", "hello"]
}

 

 

 

var array = ["hello", "world"]
array.removeAll { value in
  return value == "hello"
}
// array is now ["world"]

 

 

(참고)

https://www.donnywals.com/remove-instances-of-an-object-from-an-array-in-swift/

 

Remove instances of an object from an Array in Swift – Donny Wals

Arrays in Swift are powerful and they come with many built-in capabilities. One of these capabilities is the ability to remove objects. If you want to remove a single, specific object from an Array…

www.donnywals.com