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

后端 未结 3 1692
Happy的楠姐
Happy的楠姐 2020-12-15 02:09

Basic way doesn\'t work.

for index in 0 ..< list.count {
    if list[index] == nil {
        list.removeAtIndex(index) //this will cause array index out o         


        
相关标签:
3条回答
  • 2020-12-15 02:54

    In Swift 2.0 you can use flatMap:

    list.flatMap { $0 }
    
    0 讨论(0)
  • 2020-12-15 02:57

    Now in swift 4.2 you can use

    list.compactMap{ $0 }
    
    • list.flatMap { $0 } is already deprecated.
    0 讨论(0)
  • 2020-12-15 03:03

    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 }
    
    0 讨论(0)
提交回复
热议问题