Creating an extension to filter nils from an Array in Swift

前端 未结 7 659
难免孤独
难免孤独 2020-11-29 04:12

I\'m trying to write an extension to Array which will allow an array of optional T\'s to be transformed into an array of non-optional T\'s.

e.g. this could be writte

7条回答
  •  温柔的废话
    2020-11-29 04:28

    Swift 4

    If you are fortunate enough to be using Swift 4 then you can filter out nil values using compactMap

    array = array.compactMap { $0 }

    E.g.

    let array = [1, 2, nil, 4]
    let nonNilArray = array.compactMap { $0 }
    
    print(nonNilArray)
    // [1, 2, 4]
    

提交回复
热议问题