Swift – pruning elements from an Array, converting integer strings to integers

I have an array that contains numbers and empty strings, like ["", "2", "4", "", "", "1", "2", ""]. I would like to pare this down to a list of numbers, like [2,4,1,2].

My first effort split this into two steps, first strip out the empty strings, then do the string-to-integer conversion. However, my code for step one isn’t working as desired.

  • How to detect that parameter is a tuple of two arbitrary types?
  • Generic Swift function to test for object type
  • Converting signed to unsigned in Swift
  • Typecasting in Swift
  • Swift generic type property and method
  • Cocoa: Testing to find if an NSString is immutable or mutable?
  • for (index,value) in tempArray.enumerate(){
        if value == ""  {

    This fails, I believe because it is using the index values from the original, complete array, though after the first deletion they are not longer accurate.

    What would be a better way to accomplish my goal, and what is the best way to convert the resulting array of integer strings to an array of integers?

    2 Solutions Collect From Internet About “Swift – pruning elements from an Array, converting integer strings to integers”

    With Swift 2 we can take advantage of flatMap and Int():

    let stringsArray = ["", "2", "4", "", "", "1", "2", ""]
    let intsArray = stringsArray.flatMap { Int($0) }
    print(intsArray)  // [2, 4, 1, 2]

    Explanation: Int() returns nil if the string does not contain an integer, and flatMap ignores nils and unwraps the optional Ints returned by Int().

    var str = ["", "2", "4", "", "", "1", "2", ""]
    let filtered = str.filter {$0 != "" }
    let intArr = filtered.map {($0 as NSString).integerValue}