arr1 = ["h","e","l","l","o"] as! Any
for i in 0..<arr1.count
{
let newString:String = arr1[i] as! String
let data1:UInt8 = UInt8(newString)!
arr[i] = data1
}
答案 0 :(得分:2)
将一个字符数组转换为UInt8
并没有多大意义,因为有些字符不能仅用8位表示,例如&#34;&#34;
这是你将字符转换为[UInt32]
的方式:
let chars: [Character] = ["a", "", "c"]
let result = chars.map { UnicodeScalar($0.description)?.value }.filter{ $0 != nil }
或者,您可以使用此方法将字符转换为UInt8
,但过滤掉那些无法用8位表示的字符:
let chars: [Character] = ["a", "", "c"]
let result = chars.map { UnicodeScalar($0.description) }.filter { $0 != nil && $0!.isASCII }.map { UInt8($0!.value) }
答案 1 :(得分:2)
可以通过String
代表Character
转换UInt8
来实现
您可以使用String.UTF8View
,这是一种集合类型,现在您可以使用UInt8
轻松转换为map
。如
let charArray: [Character] = ["h","e","l","l","o"]
let arrayUInt8 = String(charArray).utf8.map { (val) -> UInt8 in
return val
}
print(charArray)
//["h", "e", "l", "l", "o"]
print(arrayUInt8)
//[104, 101, 108, 108, 111]