I have been trying to initialise a string from NSData
in Swift.
In the NSString Cocoa Documentation Apple is saying you have to use this:
init(data data: NSData!, encoding encoding: UInt)
However Apple did not include any example for usage or where to put the init
.
I am trying to convert the following code from Objective-C to Swift
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
I have been trying a lot of possible syntaxes such as the following (of course it did not work):
var string:NSString!
string = init(data: fooData,encoding: NSUTF8StringEncoding)
Since the third version of Swift you can do the following:
simialr to what Sunkas advised.
Objective - C
Swift
http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html
Another answer based on extensions (boy do I miss this in Java):
Then you can use it:
Note that the string is optional, the initial
NSData
may be unconvertible to Utf8.This is how you should initialize the
NSString
:Swift 2.X or older
Swift 3 or newer:
This doc explains the syntax.
This is the implemented code needed:
in Swift 3.0:
or just
Older swift version:
in Swift 2.0:
in Swift 1.0:
Swift 2.0
It seems that Swift 2.0 has actually introduced the
String(data:encoding:)
as an String extension when you importFoundation
. I haven't found any place where this is documented, weirdly enough.(pre Swift 2.0) Lightweight extension
Here's a copy-pasteable little extension without using
NSString
, let's cut the middle-man.This also give you access to
data.byteBuffer
which is a sequence type, so all those cool operations you can do with sequences also work, like doing areduce { $0 &+ $1 }
for a checksum.Notes
In my previous edit, I used this method:
The problem with this approach, is that I'm creating a copy of the information into a new array, thus, I'm duplicating the amount of bytes (specifically:
encoding size * data.length
)