Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Split string into Array of Int

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.

like image 708
user2924482 Avatar asked May 07 '26 20:05

user2924482


2 Answers

Use this

let stringNumbers = "1 2 10"
let array = stringNumbers.components(separatedBy: " ")
let intArray = array.map { Int($0)!} // [1, 2, 10]

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.

like image 26
rmaddy Avatar answered May 10 '26 11:05

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!