我尝试将字符串转换为数组,但显示错误
var boolean = "01101010101001010111"
我试图通过它没有工作的字符溢出字符串并尝试将其转换为数组。
resultArray = [0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,1,1]
我的代码尝试
boolean = "01101010101001010111"
let componentsArray = boolean.components(separatedBy: .controlCharacters)
resultArray = Array(componentsArray) as! [Int]
错误
错误:通用参数“无法推断元素”
答案 0 :(得分:2)
可能的解决方案:
let zeroOneString = "01101010101001010111"
let resultArray = zeroOneString.characters.flatMap { char in
char == "0" ? 0 : char == "1" ? 1 : nil
}
print(resultArray) // [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1]
zeroOneString.characters
给出所有字符的序列。
闭包将“0”映射到0
,将“1”映射到1
。其他所有内容都映射到nil
并被flatMap
忽略: