简体   繁体   English

Swift:如何将 Int 数组转换为字符数组?

[英]Swift: how to convert array of Int into array of Characters?

for instance I have an array of Int :例如我有一个Int数组:

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

Can I convert this to array of Characters: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ?我可以将其转换为字符数组: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ?

Swift doesn't implicitly convert types so this doesn't work: Swift 不会隐式转换类型,因此这不起作用:

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

Note: only 0-9 valid, digits could be unsorted.注意:只有 0-9 有效,数字可以不排序。

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] .在上面的代码中,我们从[Int]中获取每个Int ,使用 String 构造函数/初始化器将其转换为String (换句话说,我们将 String 初始化器(一个接受某些东西并返回一个字符串的函数)应用于您的[Int]使用map一个高阶函数),一旦第一个操作结束,我们将得到[String] ,第二个操作使用这个新的[String]并将其转换为[Character]

if you wish to read more on string visit here .如果您想阅读有关字符串的更多信息,请访问此处

@LeoDabus proposes the following: @LeoDabus 提出以下建议:

 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 @Alexander 提出以下建议

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.一种可能的方法是从 Ascii 代码创建Character

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

Another way is to map the Int value to a Character .另一种方法是将Int值映射到Character

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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