With Swift 5, you can use String
's init(data:encoding:)
initializer in order to convert a Data
instance into a String
instance using UTF-8. init(data:encoding:)
has the following declaration:
init?(data: Data, encoding: String.Encoding)
Returns a
String
initialized by converting given data into Unicode characters using a given encoding.
The following Playground code shows how to use it:
import Foundation
let json = """
{
"firstName" : "John",
"lastName" : "Doe"
}
"""
let data = json.data(using: String.Encoding.utf8)!
let optionalString = String(data: data, encoding: String.Encoding.utf8)
print(String(describing: optionalString))
/*
prints:
Optional("{\n\"firstName\" : \"John\",\n\"lastName\" : \"Doe\"\n}")
*/