0

I'm following a tutorial on the new Codable protocol in Swift 4. I'm retrieving JSON from iTunes.

I've setup my Data Model in a file (SearchResult.swift) that conforms to Codable:

class ResultArray: Codable {
    var resultCount = 0
    var results = [SearchResult]()
}

class SearchResult: Codable {
    var artistName = ""
    var trackName = ""

    var name: String {
        return trackName
    }
}

In my ViewController (SearchViewController.swift) I'm decoding the JSON. What I don't understand is the reference to Self in ResultArray.self. The result array object is not declared in the View Controller where I'm making the call.

func parse(data: Data) -> [SearchResult] {
        do {
            let decoder = JSONDecoder()
            let result = try decoder.decode(ResultArray.self, from: data)
            return result.results
        } catch {
            print("JSON Error: \(error)")
            return []
        }
    }
Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
Martin Muldoon
  • 3,388
  • 4
  • 24
  • 55
  • 1
    The use of `self` is for getting the `Type` because the method (https://developer.apple.com/documentation/foundation/jsondecoder/2895189-decode) is expecting a type to know to what transform the json (`data`). There a other sample where you do in that method `[SomeClass].self` to tell the decoder to transform into an array of that class. – Larme Apr 13 '18 at 13:17
  • https://developer.apple.com/documentation/foundation/jsondecoder/2895189-decode is a *generic* function, taking a type (and data), and returning a value of that type. – Martin R Apr 13 '18 at 13:17
  • Can you also post an example of the raw JSON – Mr.P Apr 13 '18 at 14:32

0 Answers0