Swift 2.1 [UInt8] --utf8->细绳?

Swift 2.1 [UInt8] --utf8->细绳?

问题描述:

我知道Stack Overflow和其他地方都存在类似的问题.但是它似乎也发展了很多.

I know questions like this exist on both Stack Overflow and elsewhere. But it seems to have evolved a lot as well.

给出一个UInt8列表(基本上是一个swift字节数组),将它隐蔽到一个迅速的String上最简单/惯用的方法是什么?

Given a list of UInt8 (a swift byte array basically), what is the easiest/idiomatic way to covert it to a swift String?

我对不使用NSData/NSString的方法特别感兴趣,因为如果Santa将Swift引入Linux的世界,那么无疑将没有NS库,并且我想知道该怎么做.只需Swift.

I'm particularly interested in the method that doesn't use NSData/NSString, since if Santa brings Swift to the world of Linux, it will undoubtedly be without the NS libraries, and I'd like to know how to do it in just Swift.

let buffUInt8: Array<UInt8> = [97, 98, 115, 100, 114, 102, 103, 104, 0]

// you need Int8 array
let buffInt8 = buffUInt8.map{ Int8(bitPattern: $0)}
let str = String.fromCString(buffInt8) // "absdrfgh"

或者您可以使用

String.fromCStringRepairingIllFormedUTF8(cs: UnsafePointer<CChar>) -> (String?, hadError: Bool)