Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

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

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...