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.

  • Initialize lazy instance variable with value that depends on other instance variables
  • 401 Forbidden when sending email with Swift and Mailgun
  • How to write Int32 to NSOutputStream in Swift
  • Method presentViewController does not work on iOS 8.3 after update
  • How to align a mask onto an image
  • Populate UITableView with NSDictionary JSON in Swift
  • 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}