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?
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.
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.
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).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With