How to convert a String (numeric) in a Int array in Swift

后端 未结 8 1431
鱼传尺愫
鱼传尺愫 2021-02-13 20:41

I\'d like to know how can I convert a String in an Int array in Swift. In Java I\'ve always done it like this:

String myString = \"123456789\";
int[] myArray = n         


        
8条回答
  •  太阳男子
    2021-02-13 20:59

    You can use flatMap to convert the characters into a string and coerce the character strings into an integer:

    Swift 2 or 3

    let string = "123456789"
    let digits = string.characters.flatMap{Int(String($0))}
    print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"
    

    Swift 4

    let string = "123456789"
    let digits = string.flatMap{Int(String($0))}
    print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"
    

    Swift 4.1

    let digits = string.compactMap{Int(String($0))}
    

    Swift 5 or later

    We can use the new Character Property wholeNumberValue https://developer.apple.com/documentation/swift/character/3127025-wholenumbervalue

    let digits = string.compactMap{$0.wholeNumberValue}
    

提交回复
热议问题