How can I unset/remove an element from an array in Apple\'s new language Swift?
Here\'s some code:
let animals = [\"cats\", \"dogs\", \"chimps\", \"m
This should do it (not tested):
animals[2...3] = []
Edit: and you need to make it a var
, not a let
, otherwise it's an immutable constant.
I use this extension, almost same as Varun's, but this one (below) is all-purpose:
extension Array where Element: Equatable {
mutating func delete(element: Iterator.Element) {
self = self.filter{$0 != element }
}
}
If you have array of custom Objects, you can search by specific property like this:
if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
doctorsInArea.remove(at: index)
}
or if you want to search by name for example
if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
doctorsInArea.remove(at: index)
}
Given
var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeFirst() // "cats"
print(animals) // ["dogs", "chimps", "moose"]
animals.removeLast() // "moose"
print(animals) // ["cats", "dogs", "chimps"]
animals.remove(at: 2) // "chimps"
print(animals) // ["cats", "dogs", "moose"]
For only one element
if let index = animals.firstIndex(of: "chimps") {
animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]
For multiple elements
var animals = ["cats", "dogs", "chimps", "moose", "chimps"]
animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]
filter
) and return the element that was removed.dropFirst
or dropLast
to create a new array.Updated to Swift 5.2
If you don't know the index of the element that you want to remove, and the element is conform the Equatable protocol, you can do:
animals.remove(at: animals.firstIndex(of: "dogs")!)
See Equatable protocol answer:How do I do indexOfObject or a proper containsObject
To remove elements from an array, use the remove(at:)
,
removeLast()
and removeAll()
.
yourArray = [1,2,3,4]
Remove the value at 2 position
yourArray.remove(at: 2)
Remove the last value from array
yourArray.removeLast()
Removes all members from the set
yourArray.removeAll()