Woodstock
Woodstock

Reputation: 22926

Using a Swift String with NSData without NSString

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

I know I can use this with 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?

Upvotes: 33

Views: 40265

Answers (3)

Irshad Qureshi
Irshad Qureshi

Reputation: 819

In Swift 2.0 You can do something like this:-

import Foundation

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

In Swift 3.0 :-

import Foundation

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

Upvotes: 3

Nick Lockwood
Nick Lockwood

Reputation: 40995

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

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

The as! is needed because NSString(...) can return nil for 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>).

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

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

var foo = datastring + "some other string"

Upvotes: 51

Anton
Anton

Reputation: 1785

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

Upvotes: 12

Related Questions