我在将UInt8Byte数组快速转换为字符串时遇到问题。我搜索并找到一个简单的解决方案
UInt8
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
但是显示错误String.type没有成员stringWithBytes。谁能建议我解决方案?
String.type
stringWithBytes
这是我要获取的代码,NSData并将其转换为字节数组,然后我必须将该字节数组转换为字符串。
NSData
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 更新 :
来自的字符串bytes: [UInt8]:
bytes: [UInt8]
if let string = String(bytes: bytes, encoding: .utf8) { print(string) } else { print("not a valid UTF-8 sequence") }
来自的字符串data: Data:
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 更新 :
if let string = String(bytes: bytes, encoding: NSUTF8StringEncoding) { print(string) } else { print("not a valid UTF-8 sequence") }
来自的字符串data: NSData:
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
stringWithBytes()
NSString
NSString(bytes: , length: , encoding: )
您可以使用的方法,但是您可以直接从创建字符串NSData,而无需UInt8数组:
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { println(str) } else { println("not a valid UTF-8 sequence") }