Removing Object from Array in Swift 3

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"}

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 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 3 - remove objects from array that exist in another array

The best (most computationally efficient) way to do this for non-trivial array sizes is to precompute a set from the array you need to repeatedly search, and filter your other array, keeping elements only if they're not found in the set.

This leverages the O(1) lookup performance of Set. The algorithm as a whole is O(userPhoneNumbers.count + contacts.count)

let userPhoneNumbers = Set(users.lazy.map{ $0.phoneNumber })
let filteredContacts = self.contacts.filter{ !userPhoneNumbers.contains($0.phoneNumber) }

Removing a specific object from an array in Swift 4

You should avoid force unwrapping in general, and your case in particular because chances are high that the array won't have an element that satisfies the condition. Instead, you can use optional binding (note that you can combine for loop with where):

func disposeOfflineEvents() {
for event in positiveEvents where !event.ongoing {
if let index = positiveEvents.index(where: { $0 === event }) {
positiveEvents.remove(at: index)
print("! - Disposing of an event!")
}
}
}

remove object from array in swift 3.0

get selected data from allflights array not from selectedFlights

        let selected = allFlights[Indexpath.row]

Swift 3 Remove objects from an array that are present in another array using set and maintaining order

Create a set with all elements from the second array,
then filter the first array to get only the elements which are not
in the set:

let array1 = [5, 4, 1, 2, 3, 4, 1, 2]
let array2 = [1, 5]

let set2 = Set(array2)
let result = array1.filter { !set2.contains($0) }

print(result) // [4, 2, 3, 4, 2]

This preserves the order (and duplicate elements) from the first
array. Using a set is advantageous if the second array can be large,
because the lookup is faster.



Related Topics



Leave a reply



Submit