Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all nil elements in a Swift array?

Tags:

ios

swift

Basic way doesn't work.

for index in 0 ..< list.count {     if list[index] == nil {         list.removeAtIndex(index) //this will cause array index out of range     } } 
like image 207
TIMEX Avatar asked Jul 22 '15 18:07

TIMEX


People also ask

How do you remove nil from an array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

How do you empty an array in Swift?

To create an empty string array in Swift, specify the element type String for the array and assign an empty array to the String array variable.

What is compactMap in Swift?

Swift version: 5.6. The compactMap() method lets us transform the elements of an array just like map() does, except once the transformation completes an extra step happens: all optionals get unwrapped, and any nil values get discarded.

What is array reduce in Swift?

Swift version: 5.6. The reduce() method iterates over all items in array, combining them together somehow until you end up with a single value.


2 Answers

The problem with your code is that 0 ..< list.count is executed once at the beginning of the loop, when list still has all of its elements. Each time you remove one element, list.count is decremented, but the iteration range is not modified. You end up reading too far.

In Swift 4.1 and above, you can use compactMap to discard the nil elements of a sequence. compactMap returns an array of non-optional values.

let list: [Foo?] = ... let nonNilElements = list.compactMap { $0 } 

If you still want an array of optionals, you can use filter to remove nil elements:

list = list.filter { $0 != nil } 
like image 112
zneak Avatar answered Sep 30 '22 10:09

zneak


In Swift 2.0 you can use flatMap:

list.flatMap { $0 } 
like image 24
Marcel Molina Avatar answered Sep 30 '22 11:09

Marcel Molina