Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Specific Array Element, Equal to String - Swift

Is there no easy way to remove a specific element from an array, if it is equal to a given string? The workarounds are to find the index of the element of the array you wish to remove, and then removeAtIndex, or to create a new array where you append all elements that are not equal to the given string. But is there no quicker way?

like image 388
TimWhiting Avatar asked Jan 10 '15 17:01

TimWhiting


People also ask

How to remove specific element from array in ios Swift?

Method 1 − Using the filter method of the array. Arrays in swift have a filter method, which filters the array object depending on some conditions and returns an array of new objects.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you delete an array in Swift?

To remove an element from the Swift Array, use array. remove(at:index) method. Remember that the index of an array starts at 0. If you want to remove ith element use the index as (i-1).


1 Answers

You can use filter() to filter your array as follow

var strings = ["Hello","Playground","World"]  strings = strings.filter { $0 != "Hello" }  print(strings)   // "["Playground", "World"]\n" 

edit/update:

Xcode 10 • Swift 4.2 or later

You can use the new RangeReplaceableCollection mutating method called removeAll(where:)

var strings = ["Hello","Playground","World"]  strings.removeAll { $0 == "Hello" }  print(strings)   // "["Playground", "World"]\n" 

If you need to remove only the first occurrence of an element we ca implement a custom remove method on RangeReplaceableCollection constraining the elements to Equatable:

extension RangeReplaceableCollection where Element: Equatable {     @discardableResult     mutating func removeFirst(_ element: Element) -> Element? {         guard let index = firstIndex(of: element) else { return nil }         return remove(at: index)     } } 

Or using a predicate for non Equatable elements:

extension RangeReplaceableCollection {     @discardableResult     mutating func removeFirst(where predicate: @escaping (Element) throws -> Bool) rethrows -> Element? {         guard let index = try firstIndex(where: predicate) else { return nil }         return remove(at: index)     } } 

var strings = ["Hello","Playground","World"] strings.removeFirst("Hello") print(strings)   // "["Playground", "World"]\n" strings.removeFirst { $0 == "Playground" } print(strings)   // "["World"]\n" 
like image 195
Leo Dabus Avatar answered Sep 25 '22 17:09

Leo Dabus