Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a string from NSData in Swift

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)
like image 734
ahmed Avatar asked Sep 26 '22 07:09

ahmed


People also ask

What is difference between string and NSString in Swift?

The Swift string is one character long, as expected. The NSString says it has a length of seven — this matches with the length of the Swift string's utf16 view, since NSStrings are backed by UTF-16: 09:02 The Swift string's unicodeScalars view returns a count of four.


1 Answers

This is the implemented code needed:

in Swift 3.0:

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

or just

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

Older swift version:

in Swift 2.0:

import Foundation

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

in Swift 1.0:

var dataString = NSString(data: fooData, encoding:NSUTF8StringEncoding)
like image 282
Sunkas Avatar answered Oct 13 '22 14:10

Sunkas