UnknownUser UnknownUser - 7 months ago 15
Swift Question

How to remove an element from an array in Swift

How can I unset/remove an element from an array in Apple's new language Swift?

Here's some code:

var animals = ["cats", "dogs", "chimps", "moose"]


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

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.removeAtIndex(2)  //["cats", "dogs", "moose"]
Comments