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

查看:72
本文介绍了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)

这篇关于Swift 2.1 [UInt8] --utf8->细绳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆