Swift Language Convert String to and from Data / NSData


Example

To convert String to and from Data / NSData we need to encode this string with a specific encoding. The most famous one is UTF-8 which is an 8-bit representation of Unicode characters, suitable for transmission or storage by ASCII-based systems. Here is a list of all available String Encodings

String to Data/NSData

3.0
let data = string.data(using: .utf8)
2.2
let data = string.dataUsingEncoding(NSUTF8StringEncoding)

Data/NSData to String

3.0
let string = String(data: data, encoding: .utf8)
2.2
let string = String(data: data, encoding: NSUTF8StringEncoding)