Skip to content

Instantly share code, notes, and snippets.

@vzsg
Created May 22, 2019 21:29
Show Gist options
  • Save vzsg/c9579e09a2cc9fc40d33d7cccc8f9b4e to your computer and use it in GitHub Desktop.
Save vzsg/c9579e09a2cc9fc40d33d7cccc8f9b4e to your computer and use it in GitHub Desktop.
Parsing parallel arrays of the Wikipedia API with Codable
import Foundation
struct WikipediaEntry {
let title: String
let summary: String
let link: URL?
}
struct WikipediaSearchResults: Decodable {
let term: String
let entries: [WikipediaEntry]
init(from decoder: Decoder) throws {
var uc = try decoder.unkeyedContainer()
self.term = try uc.decode(String.self)
let titles = try uc.decode([String].self)
let summaries = try uc.decode([String].self)
let urls = try uc.decode([String].self)
.map { URL(string: $0 )}
entries = zip(zip(titles, summaries), urls)
.map { WikipediaEntry(title: $0.0.0, summary: $0.0.1, link: $0.1) }
}
}
URLSession.shared.dataTask(with: URL(string: "https://en.wikipedia.org/w/api.php?action=opensearch&search=Man&format=json")!) { data, resp, error in
guard let data = data else {
return
}
let decoder = JSONDecoder()
let results = try? decoder.decode(WikipediaSearchResults.self, from: data)
print(results)
}.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment