O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using JSONEncoder

JSONEncoder will encode instances of types that conform to the Codable typealias, as JSON objects. The following code illustrates how to do this:

let book1 = Book(name: "Mastering Swift 3", author: "Jon Hoffman", publisher: "Packt Publishing") 
 
let encoder = JSONEncoder() 
let data = try? encoder.encode(book1) 

This code starts off by creating an instance of the Book and JSONEncoder() types. Next the encode method of the JSONEncoder is used to encode the Book instance to a JSON object. If the encode method fails it will return nil; otherwise it will return an instance of a Data object. We can convert this object to an instance of the string type as shown in the following code:

if let data = data, let dataString = String(data: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required