如何在 Swift 中将 UInt8 字节数组转换为字符串 [英] How to convert UInt8 byte array to string in Swift

查看:114
本文介绍了如何在 Swift 中将 UInt8 字节数组转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在快速将 UInt8 字节数组转换为字符串时遇到问题.我已经搜索并找到了一个简单的解决方案

I am facing problems while converting UInt8 Byte array to string in swift. I have searched and find a simple solution

String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)

但它显示错误 String.type 没有成员 stringWithBytes.谁能建议我一个解决方案?

but it is showing error String.type does not have a member stringWithBytes. Can anyone suggest me a solution ?

这是我的代码,我在其中获取 NSData 并转换为字节数组,然后我必须将该字节数组转换为字符串.

this is my code where i am getting anNSData and converted into bytes array and then i have to convert that byte array into string.

let count = data.length / sizeof(UInt8)
var array = [UInt8](count: count, repeatedValue: 0)
data.getBytes(&array, length:count * sizeof(UInt8))
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)

推荐答案

Swift 3/Xcode 8 更新:

来自字节的字符串:[UInt8]:

if let string = String(bytes: bytes, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: Data:

String from data: Data:

let data: Data = ...
if let string = String(data: data, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

<小时>

Swift 2/Xcode 7 的更新:

来自字节的字符串:[UInt8]:

if let string = String(bytes: bytes, encoding: NSUTF8StringEncoding) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: NSData:

String from data: NSData:

let data: NSData = ...
if let str = String(data: data, encoding: NSUTF8StringEncoding) {
    print(str)
} else {
    print("not a valid UTF-8 sequence")
}

<小时>

上一个答案:

String 没有 stringWithBytes() 方法.NSString 有一个

String does not have a stringWithBytes() method. NSString has a

 NSString(bytes: , length: , encoding: )

您可以使用的方法,但您可以直接从 NSData 创建字符串,而无需 UInt8 数组:

method which you could use, but you can create the string directly from NSData, without the need for an UInt8 array:

if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
    println(str)
} else {
    println("not a valid UTF-8 sequence")
}

这篇关于如何在 Swift 中将 UInt8 字节数组转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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