简体   繁体   中英

Swift: how to convert array of Int into array of Characters?

for instance I have an array of Int :

let digits = [Int](0...9)

Can I convert this to array of Characters: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ?

Swift doesn't implicitly convert types so this doesn't work:

let digits: Array<Character> = [Int](0...9)

Note: only 0-9 valid, digits could be unsorted.

func convertArray(array: [Int]) -> [Character] {
    return array.map {
        Character(String($0))
    }
}

Try this:

Array(0...9).map({String($0)}).map({ Character($0) })

In the code above, we are taking each Int from [Int] , transform it into String using the String constructor/initializer (in order words we're applying the String initializer (a function that takes something and returns a string) to your [Int] using map an higher order function), once the first operation is over we'd get [String] , the second operation uses this new [String] and transform it to [Character] .

if you wish to read more on string visit here .

@LeoDabus proposes the following:

 Array(0...9).map(String.init).map(Character.init)  //<-- no need for closure

Or instead of having two operations just like we did earlier, you can do it with a single iteration.

Array(0...9).map({Character("\\($0)")})

@Alexander proposes the following

Array((0...9).lazy.map{ String($0) }.map{ Character($0) })

(0...9).map{ Character(String($0)) } //<-- where you don't need an array, you'd use your range right away

Try this

 var arrChars = [string]()

 for i in 0..<digits.count
 {

    let item = digits[i]

    arrChars.append("\(item)")

 }

只需使用map功能:

let stringArray = digits.map{String($0)}

One possible way is to create the Character from Ascii codes.

let charArrFromAscii = Array(48...57).map({ Character(UnicodeScalar($0)) })

Another way is to map the Int value to a Character .

let charArrFromInt = Array(0...9).map({ Character("\($0)") })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM