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: ...