3

I'm trying to split string into Array Of integers:

let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.characters.flatMap{Int(String($0))}

But my problem is I'm getting this output:

[1, 2, 1, 0]

When I should be getting this output:

[1, 2, 10]

What I'm doing wrong?

I'll really appreciate your help.

2
  • Possible duplicate of Converting a String to an Int Array Commented Feb 25, 2017 at 2:40
  • Well you're converting every separate character into integers. All multi-digit numbers have their digits be interpreted as seperate, single-digit numbers. Commented Feb 25, 2017 at 2:41

3 Answers 3

7

Use this

let stringNumbers = "1 2 10"
let array = stringNumbers.components(separatedBy: " ")
let intArray = array.map { Int($0)!} // [1, 2, 10]
Sign up to request clarification or add additional context in comments.

3 Comments

Careful using !. While it won't cause problems with this specific string, it will crash if the string actually contains any text that can't be converted to a number.
Agreed with rmaddy
When the first number is 0, it wont be added to the final array, what to do there?
4

You are converting the individual characters of the strings into numbers. First the 1, then the space, then the 2, then the space, then the 1, and lastly the 0. If course converting the space gives a nil with is filtered out by using flatMap.

You can do:

let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.components(separatedBy: " ").flatMap { Int($0) }

This splits the original string into an array of strings (separated by a space) and then maps those into integers.

5 Comments

the I print you solution I'm getting "[Optional(1), Optional(2), Optional(10)]". How can I just print the array of numbers ?
let arrayIntegers = stringNumbers.components(separatedBy: " ").flatMap{ Int($0) }
@LeoDabus Thanks. Updated. Forgot just using map will give an array of optionals in this case. And using flatMap leaves out any nil values if the string contains any text that can't be converted to a number.
you can also use this for null value let arrayIntegers = stringNumbers.components(separatedBy: " ").flatMap{ Int($0) as? String ?? "" }
@seggy There's no need to use ?? with flatMap. And Int will never be a String so it makes no sense at all.
1

In Swift 5 it is:

let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.split(separator: " ").compactMap { Int($0) }

1 Comment

Alternative for Swift 5: stringNumbers.components(separatedBy: .whitespaces).compactMap { Int($0) }. You can also use .whitespacesAndNewlines to split by newlines too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.