Advertisement
Advertisement


How to remove an element from an array in Swift


Question

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", "moose"]

How could the element animals[2] be removed from the array?

2016/06/09
1
242
6/9/2016 12:55:30 PM

Accepted Answer

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" }
2017/06/22
313
6/22/2017 2:39:16 PM


The above answers seem to presume that you know the index of the element that you want to delete.

Often you know the reference to the object you want to delete in the array. (You iterated through your array and have found it, e.g.) In such cases it might be easier to work directly with the object reference without also having to pass everywhere its index. Hence, I suggest this solution. It uses the identity operator !==, which you use to test whether two object references both refer to the same object instance.

func delete(element: String) {
    list = list.filter() { $0 !== element }
}

Of course this doesn't just work for Strings.

2017/05/23

Swift 5: Here is a cool and easy extension to remove elements in an array, without filtering :

   extension Array where Element: Equatable {

    // Remove first collection element that is equal to the given `object`:
    mutating func remove(object: Element) {
        guard let index = firstIndex(of: object) else {return}
        remove(at: index)
    }

}

Usage :

var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"

myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]

Also works with other types, such as Int since Element is a generic type:

var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17

myArray.remove(object: objectToRemove) // [4, 8, 6, 2]
2019/12/15

For Swift4:

list = list.filter{$0 != "your Value"}
2018/01/04

As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows

Apple's example:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]

phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."

see Apple's Documentation

So in the OP's example, removing animals[2], "chimps":

var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }

This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.

2018/06/20

Few Operation relates to Array in Swift

Create Array

var stringArray = ["One", "Two", "Three", "Four"]

Add Object in Array

stringArray = stringArray + ["Five"]

Get Value from Index object

let x = stringArray[1]

Append Object

stringArray.append("At last position")

Insert Object at Index

stringArray.insert("Going", atIndex: 1)

Remove Object

stringArray.removeAtIndex(3)

Concat Object value

var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
2015/06/27