使用swift的NSString initWithBytes

时间:2014-11-05 23:25:20

标签: swift nsstring

尝试转换(工作)objC代码:

const uint8_t * buffer = ...
NSString * password = [[NSString alloc] initWithBytes:buffer+28 length:buffer[27] encoding:NSUTF8StringEncoding];

尝试:

let buffer: [Byte] = ...
var password = NSString(bytes: buffer+28, length: Int(buffer[27]), encoding: NSUTF8StringEncoding)

但是这会立即崩溃SourceKitService,如果我尝试编译则会编译器。

我怀疑它可能与转换指针有关吗?

1 个答案:

答案 0 :(得分:3)

如果您需要将字节数组转换为NSString,则只需使用

构造它
NSString(bytes: buffer, length: buffer.length, encoding: NSUTF8StringEncoding)

如果你需要进行指针前进等,那么将它转换为UnsafePointer,如下所示:

NSString(bytes: UnsafePointer<Byte>(buffer) + 28, length: Int(buffer[27]), encoding: NSUTF8StringEncoding)