How to remove multiple items from a swift array?
Given your array
var numbers = [1, 2, 3, 4]
and a Set
of indexes you want to remove
let indexesToRemove: Set = [1, 3]
You want to remove the values "2" and "4".
Just write
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
Result
print(numbers) // [1, 3]
Swift 3 Array, remove more than one item at once, with .remove(at: i)
It's possible if the indexes are continuous using removeSubrange
method.
For example, if you would like to remove items at index 3 to 5:
myArray.removeSubrange(ClosedRange(uncheckedBounds: (lower: 3, upper: 5)))
For non-continuous indexes, I would recommend remove items with larger index to smaller one. There is no benefit I could think of of removing items "at the same time" in one-liner except the code could be shorter. You can do so with an extension method:
extension Array {
mutating func remove(at indexes: [Int]) {
for index in indexes.sorted(by: >) {
remove(at: index)
}
}
}
Then:
myArray.remove(at: [3, 5, 8, 12])
UPDATE: using the solution above, you would need to ensure the indexes array does not contain duplicated indexes. Or you can avoid the duplicates as below:
extension Array {
mutating func remove(at indexes: [Int]) {
var lastIndex: Int? = nil
for index in indexes.sorted(by: >) {
guard lastIndex != index else {
continue
}
remove(at: index)
lastIndex = index
}
}
}
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
myArray.remove(at: [5, 3, 5, 12]) // duplicated index 5
// result: [0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 13] only 3 elements are removed
Remove multiple indices from array
Rather than a list of indices to remove, it may be easier to have a list of indices to keep, which you can do using the Set
type:
let rmIndices = [1,4,5]
let keepIndices = Set(arr.indices).subtract([1,4,5])
Then you can use PermutationGenerator
to create a fresh array of just those indices:
arr = Array(PermutationGenerator(elements: arr, indices: keepIndices))
Swift 3 array - remove multiple elements with help of other array
Your array arrayIndex
is look like Array of Int
not array of IndexPath
.
arrayIndex.sorted(by: >).forEach { if $0 < self.arrayString.count { self.arrayString.remove(at: $0) } }
If arrayIndex
is Array of IndexPath
then use row
property to remove the object from array.
arrayIndex.sorted(by: { $0.row > $1.row }).forEach { if $0.row < self.arrayString.count { self.arrayString.remove(at: $0.row) } }
Removing object from array in Swift 3
The Swift equivalent to NSMutableArray
's removeObject
is:
var array = ["alpha", "beta", "gamma"]
if let index = array.firstIndex(of: "beta") {
array.remove(at: index)
}
if the objects are unique. There is no need at all to cast to NSArray
and use indexOfObject:
The API index(of:
also works but this causes an unnecessary implicit bridge cast to NSArray
.
Of course you can write an extension of RangeReplaceableCollection
to emulate the function. But due to value semantics you cannot name it removeObject
.
extension RangeReplaceableCollection where Element : Equatable {
@discardableResult
mutating func remove(_ element : Element) -> Element?
{
if let index = firstIndex(of: element) {
return remove(at: index)
}
return nil
}
}
Like remove(at:
it returns the removed item or nil
if the array doesn't contain the item.
If there are multiple occurrences of the same object use filter
. However in cases like data source arrays where an index is associated with a particular object firstIndex(of
is preferable because it's faster than filter
.
Update:
In Swift 4.2+ you can remove one or multiple occurrences of beta
with removeAll(where:)
:
array.removeAll{$0 == "beta"}
How to remove an element from an array in Swift
The let
keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var
instead, e.g:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2) //["cats", "dogs", "moose"]
A non-mutating alternative that will keep the original collection unchanged is to use filter
to create a new collection without the elements you want removed, e.g:
let pets = animals.filter { $0 != "chimps" }
Swift: Better way to remove a specific Object from an array?
Use firstIndex(where:)
(previously called index(where:)
in Swift 4.1 and earlier) to search the array for your object using the predicate { $0 === objectToRemove }
, then call remove(at:)
on the array to remove it:
if let idx = objectArray.firstIndex(where: { $0 === objectToRemove }) {
objectArray.remove(at: idx)
}
This allows you to search for your object whether it is Equatable
or not.
How to remove an element from array of object on swift based on id?
loop through all the indexes of the array and check if the id you want to delete matches, if yes it will filter out and you can remove that index :-)
let idToDelete = 10
if let index = arrStudents.index(where: {$0.id == idToDelete}) {
array.remove(at: index)
}
if you want to remove multiple value in single iteration you should start the loop from last index to first index, so it will not crash (out of bound error )
var idsToDelete = [10, 20]
for id in idsToDelete {
for (i,str) in arrStudents.enumerated().reversed()
{
if str.id == id
{
arrStudents.remove(at: i)
}
}
}
Removing duplicate elements from an array in Swift
You can roll your own, e.g. like this:
func unique<S : Sequence, T : Hashable>(source: S) -> [T] where S.Iterator.Element == T {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60]
And as an extension for Array
:
extension Array where Element: Hashable {
func uniqued() -> Array {
var buffer = Array()
var added = Set<Element>()
for elem in self {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
}
Or more elegantly (Swift 4/5):
extension Sequence where Element: Hashable {
func uniqued() -> [Element] {
var set = Set<Element>()
return filter { set.insert($0).inserted }
}
}
Which would be used:
[1,2,4,2,1].uniqued() // => [1,2,4]
Related Topics
Property Cannot Be Declared Public Because Its Type Uses an Internal Type
Convert Swift Dictionary to String
Swift Uisearchcontroller Wired Up in Core Data Project, App Runs, But Search Not Updating
How to Implement a Thread Safe Hashtable (Phonebook) Data Structure in Swift
Is Self Captured Within a Nested Function
Nested Types Inside a Protocol
Codable and Xmlparser in Swift
Optionals VS Throwing Functions
Nspredicate with Swift and Core Data
Subclassing VS Extension in Swift
How to Record Video in Realitykit
Swift Struct Doesn't Conform to Protocol Equatable
Why Is There a Memory Leak at String Creation in Swift
Conflicting Definition of Swift Struct and Array
Storyboard Entry Point Missing
Swiftui Navigationview Trying to Pop to Missing Destination (Monoceros)