0

So if I had an array of strings and I wanted to pull out all of the integers (as Strings), how could I do this?

For example:

myArray = ["1","2","3","unknown","bob"]

I've tried

myArray.filter { Int($0) }

But I get an error telling me I can't convert Int? to Bool

  • 2
    Do you want the resulting array to be the original strings that can be converted to `Int` or do you want the resulting array to contain the corresponding `Int` values of the strings that can be converted? – rmaddy Apr 09 '17 at 02:49
  • Can you clarify exactly what output you would like for this given input? – Alexander Apr 09 '17 at 02:52
  • I need strings, sorry I didn't clarify. –  Apr 09 '17 at 04:28

3 Answers3

1

You almost had it.

Swift 3

let filteredArray = myArray.filter { Int($0) != nil }
John R Perry
  • 3,916
  • 2
  • 38
  • 62
  • 2
    Note that filter is a non mutating method. myArray will not change so you need to assign the result to a new object. – Leo Dabus Apr 09 '17 at 03:24
1

Simply, like this:

let myArray = ["1","2","3","unknown","bob"]
let filteredArray = myArray.filter { Int($0) != nil }
print(filteredArray) // ["1", "2", "3"]

Note that filteredArray is [String]. To get it as [Int], you should use map:

let filteredArray = myArray.filter { (Int($0) != nil) }.map { Int($0)! }
print(filteredArray) // [1, 2, 3]
Alexander
  • 59,041
  • 12
  • 98
  • 151
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • A better approach to the second code snippet is to just use `flatMap`: `myArray.flatMap{ Int($0 }`, or even better: `myArray.flatMap(Int.init)` – Alexander Apr 09 '17 at 02:50
  • @Alexander could you please explain -simply- why `myArray.flatMap(Int.init)` would be better than `myArray.flatMap{ Int($0 }`? – Ahmad F Apr 09 '17 at 06:04
  • It's actually not possible in this case, because the initializer that takes a `String` and returns an `Int?` also has an `Int` argument that specifies the radix. This is defaulted to `10`, but it changes the type signature so that this doesn't work. – Alexander Apr 09 '17 at 06:27
0

If you want to only keep the integers that can successfully be converted, then use flatMap:

let strings = ["1", "2", "3", "unknown", "bob"]
let numbers = strings.flatMap{ Int($0) } // => [1, 2, 3]
Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • This is why I posted my comment below the question. I was going to propose this if the desired result is the `Int` values. If the desired result is the original strings, then this won't work. – rmaddy Apr 09 '17 at 02:55
  • 1
    BTW - the syntax is all wrong. You want `let numbers = strings.flatMap { Int($0) }`. – rmaddy Apr 09 '17 at 02:59
  • @rmaddy Oh yeah, that initializer has a defaulted `radix` parameter that makes it impossible to use like this. – Alexander Apr 09 '17 at 03:34
  • I like this answer too! –  Apr 09 '17 at 04:29