ios 在没有 NSString 的情况下使用带有 NSData 的 Swift 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24096446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:38:22  来源:igfitidea点击:

Using a Swift String with NSData without NSString

iosswift

提问by Woodstock

Is it possible to init a Swift string (not NSString) with the contents of an NSData object without creating an NSString first?

是否可以在NSString不先创建 NSString 的情况下使用 NSData 对象的内容初始化 Swift 字符串(不是)?

I know I can use this with NSString:

我知道我可以将它与 NSString 一起使用:

var datastring = NSString(data data: NSData!, encoding encoding: UInt)

But how can I use a basic Swift String type? I thought Swift strings and NSStrings were interchangeable, do I really have to get the data out of NSData using NSString and then assign that value to a Swift string?

但是如何使用基本的 Swift String 类型呢?我认为 Swift 字符串和 NSStrings 是可以互换的,我真的必须使用 NSString 从 NSData 中获取数据,然后将该值分配给 Swift 字符串吗?

回答by Nick Lockwood

As of Swift 1.2 they aren't quite interchangeable, but they are convertible, so there's really no reason not to use NSStringand its constructors when you need to. This will work fine:

从 Swift 1.2 开始,它们并不是完全可以互换的,但是它们是可转换的,因此NSString在需要时确实没有理由不使用及其构造函数。这将正常工作:

var datastring = NSString(data:data, encoding:NSUTF8StringEncoding) as! String

The as!is needed because NSString(...)can return nilfor invalid input - if you aren't sure that the data represents a valid UTF8 string, you may wish to use the following instead to return a String?(aka Optional<String>).

as!是必要的,因为NSString(...)可以返回nil了无效的输入-如果你不知道该数据代表一个有效的UTF8字符串,你不妨改用以下返回一个String?(又名Optional<String>)。

var datastring = NSString(data:data, encoding:NSUTF8StringEncoding) as String?

Once constructed, you can then use datastringjust like any other Swift string, e.g.

一旦构造完成,您就可以datastring像使用任何其他 Swift 字符串一样使用,例如

var foo = datastring + "some other string"

回答by Anton

var buffer = [UInt8](count:data.length, repeatedValue:0)
data.getBytes(&buffer, length:data.length)
var datastring = String(bytes:buffer, encoding:NSUTF8StringEncoding)

回答by Irshad Qureshi

In Swift 2.0 You can do something like this:-

在 Swift 2.0 中,您可以执行以下操作:-

import Foundation

var dataString = String(data: YourData, encoding: NSUTF8StringEncoding)

In Swift 3.0 :-

在 Swift 3.0 中:-

import Foundation

var dataString = String(data: data, encoding: String.Encoding.utf8)