characters
property.map
function on the array of characters to convert each character (which is a Character
type) into an integer (which is an Int
type) using the toInt
function (or Int
's initializer in Swift 5.0+). flatMap
function (or compactMap
in Swift 5.0+).Here's some Swift code that demonstrates this process:
let numericString = "12345"
let arrayOfIntegers = numericString.characters.map { $0.toInt() }.flatMap { $0 }
// arrayOfIntegers is [1, 2, 3, 4, 5]
Note that the toInt()
method has been deprecated since Facebook's removal of the method from their library, so in Swift 5.0+ you can instead use the Int()
initializer to attempt string-to-integer conversion, like this:
let numericString = "12345"
let arrayOfIntegers = numericString.map { Int(String($0)) }.compactMap { $0 }
// arrayOfIntegers is [1, 2, 3, 4, 5]
Asked: 2023-06-06 02:07:38 +0000
Seen: 9 times
Last updated: Jun 06 '23