Ben Ben - 2 months ago 34
Swift Question

Swift: safely convert list of comma-separated numbers in a string to an array of Ints

I would like to create an array of integers, [Int] from a string which should contain a list comma seperated numbers.

Here are some valid inputs:

1
1,2,3
1,5,10


Here are some invalid inputs:

[nil] // no value set
1,,2,3 // extra commas
1,Z,10 // characters other than numbers and commas


I've managed to come up with something for the first part, i.e. separating the values out, using this code:

func get_numbers() -> Array<Int>{
return self.numbers_as_csv_string!
.components(separatedBy: ",")
.map { word in Int(word.trimmingCharacters(in: CharacterSet.whitespaces))! }
}


Unfortunately, that code doesn't deal with invalid inputs as listed above and the app will just crash in most cases. What is the best way of adding in some checks to this, so that if an invalid list is present, we just return a
[1]
? I'd like the shortest code possible - is a regex the best way to go here?

Many thanks in advance!

Answer

Instead of using ! to force unwrap, use flatMap to ignore components that cannot be converted to Int:

func get_numbers() -> Array<Int> {
    return self.numbers_as_csv_string!
        .components(separatedBy: ",")
        .flatMap {
            Int($0.trimmingCharacters(in: .whitespaces))
        }
}

Sample results:

1           => [1]
1,2,3       => [1,2,3]
1,5,10      => [1,5,10]

nil         => []
1,,2,3      => [1,2,3]
1,Z,10      => [1,10]