如何在swift 3中从CChar更改为Data

时间:2017-03-16 08:56:43

标签: swift

我在使用GBK编码将CChar更改为Data时遇到问题。有人可以给我一些如何做的提示,它会有很大帮助 语法似乎发生了变化,所以我对如何做到这一点感到有点难过

之前更改为NSData但由于语法已更改为Data,我不太清楚如何进行交换。

let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringENcoding(CFStringEncoding(cfEnc.rawValue))
let ccharStr = "aaa".cString(using: String.Encoding(rawValue: enc))!
let tmp = NSData(bytes: ccharStr, length: ccharStr.count)
self.writeValue(tmp)

现在我已经改为

let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

let aaa = "aaa\n"
var stringCChar = aaa.cString(using: String.Encoding(rawValue: enc))
let stringData = Data(bytes: &stringCChar, count: (stringCChar?.count)!) // but this exchange can't show the correct result...
self.writeValue(stringData)

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

中的问题
let stringData = Data(bytes: &stringCChar, count: (stringCChar?.count)!)

是您将可选的地址传递给Data 构造函数,表示读取struct Optional的内存内容,而不是字符数据。

所以你必须打开stringCChar,例如可选绑定:

let str = "your String"

let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

if let stringCChar = str.cString(using: String.Encoding(rawValue: enc)) {
    let stringData = Data(bytes: stringCChar, count: stringCChar.count)
    // ...
} else {
    // cannot encode string in GB_18030_2000
}

一个稍微简单的解决方案是

let str = "your String"

let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

if let stringData = str.data(using: String.Encoding(rawValue: enc)) {
    // ....
} else {
    // cannot encode string in GB_18030_2000
}

请注意,第一个解决方案将在数据中包含尾随零(C字符串终结符),而第二个解决方案不包含。