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 } }
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
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.
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.
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.
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 }
In Swift 2.0 you can use flatMap:
list.flatMap { $0 }
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