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

后端 未结 8 1421
鱼传尺愫
鱼传尺愫 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:49

    Swift 3: Functional Approach

    1. Split the String into separate String instances using: components(separatedBy separator: String) -> [String]

    Reference: Returns an array containing substrings from the String that have been divided by a given separator.

    1. Use the flatMap Array method to bypass the nil coalescing while converting to Int

    Reference: Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

    Implementation

    let string = "123456789"
    let intArray = string.components(separatedBy: "").flatMap { Int($0) }
    

提交回复
热议问题