我在swift中有一系列角色:
static let charArray: [Character] = [ "S", "t", "r", "i", "n", "g"]
我想对每个Character
做一些逐位运算作为一个字节(UInt8
)。例如,如何将charArray[0]
转换为UInt8
?
答案 0 :(得分:12)
您需要通过String
:s的Character
代表转换为UInt8
。但是,您无需在[Character] -> [UInt8]
转换中显式初始化数组;由于String.UTF8View
(来自String.utf8
)是CollectionType
,因此您可以对map
本身应用String.UTF8View
操作;初始化为UInt8
。即,
let charArray: [Character] = [ "S", "t", "r", "i", "n", "g"]
let asUInt8Array = String(charArray).utf8.map{ UInt8($0) }
print(asUInt8Array)
/* [83, 116, 114, 105, 110, 103] */
print(asUInt8Array.dynamicType)
/* Array<UInt8> */
关于你在下面的评论(“对于Swift的抽象感到沮丧,与Objective-C的简单方式相比”):如果你认为上述内容很混乱,你可以包括它在SequenceType
的扩展中限制为Character
元素,允许在实践中更容易使用。 E.g:
extension SequenceType where Generator.Element == Character {
/* extension accessible as function */
func asByteArray() -> [UInt8] {
return String(self).utf8.map{UInt8($0)}
}
/* or, as @LeoDabus pointed out below (thanks!),
use a computed property for this simple case */
var byteArray : [UInt8] {
return String(self).utf8.map{UInt8($0)}
}
}
用法示例:
let charArray: [Character] = [ "S", "t", "r", "i", "n", "g"]
/* use extension function */
let asUInt8Array = charArray.asByteArray()
/* or computed property */
let asUInt8Array = charArray.byteArray
答案 1 :(得分:4)
我不确定如何将字符转换为UTF-8,但字符串具有utf8
属性,因此您可以使用以下内容:
let charArray: [Character] = [ "S", "t", "r", "i", "n", "g"]
let string = Array(String(charArray).utf8)
print(string)
答案 2 :(得分:2)
这就是我最终做到的方式:
var char: Character = "a"
var byte: UInt8 = Array(String(char).utf8)[0]
必须有更好的方法......
答案 3 :(得分:0)
改善@dfri回答https://stackoverflow.com/a/36025104/1979882
Swift 3 你必须使用它:
extension Sequence where Iterator.Element == Character {
/* extension accessible as function */
func asByteArray() -> [UInt8] {
return String(self).utf8.map{UInt8($0)}
}
/* or, as @LeoDabus pointed out below (thanks!),
use a computed property for this simple case */
var byteArray : [UInt8] {
return String(self).utf8.map{UInt8($0)}
}
}