NSData到Swift问题中的字符串 [英] NSData to String in Swift Issues

查看:89
本文介绍了NSData到Swift问题中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在快速将NSData转换为NSString时遇到问题.我使用的是我认为正确的命令和格式:NSString(data: <DATA>, encoding: <ENCODING>)但是无论如何我都以nil值结尾.我正在运行最新的Xcode beta,所以我不确定是否与此相关,但是我希望它是我遇到的一个简单错误.

I'm having issues converting my NSData to NSString in swift. I'm using what I think is the correct command and format: NSString(data: <DATA>, encoding: <ENCODING>) however whatever I do i keep ending up with a nil value. I am running the latest Xcode beta so I'm not sure if that is related but I'm hoping its a simple easy error that I've run into.

我已经附加了游乐场代码和屏幕截图.

I've attached playground code as well as a screen capture.

import Foundation

//: # NSData to String Conversion Playground
//: ### Step 1
//: The first step is to take an array of bytes and conver them into a NSData object.  The bytes are as follows:

var testBytes : [UInt8] = [0x14, 0x00, 0xAB, 0x45, 0x49, 0x1F, 0xEF, 0x15, 0xA8, 0x89, 0x78, 0x0F, 0x09, 0xA9, 0x07, 0xB0, 0x01, 0x20, 0x01, 0x4E, 0x38, 0x32, 0x35, 0x56, 0x20, 0x20, 0x20, 0x00]

//: ### Step 2
//: Convert the byte array into an **NSData** Object

var immutableData = NSData(bytes: testBytes, length: testBytes.count)

//: ### Step 3
//: Attempt to convert the **NSData** object into a string so it can be sent around as ascii.  This for some reason seems to be failing, however.

var convertedString = NSString(data: immutableData, encoding: NSUTF8StringEncoding)

println("String = \(convertedString)")

Playgound的结果

推荐答案

let testBytes : [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]


func bytes2String(array:[UInt8]) -> String {
    return String(data: NSData(bytes: array, length: array.count), encoding: NSUTF8StringEncoding) ?? ""
}

Xcode 8.2•Swift 3.0.2

func bytes2String(_ array: [UInt8]) -> String {
    return String(data: Data(bytes: array, count: array.count), encoding: .utf8) ?? ""
}


测试:


Testing:

bytes2String(testBytes)  // "Hello World"

这篇关于NSData到Swift问题中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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