Created
May 22, 2019 21:29
-
-
Save vzsg/c9579e09a2cc9fc40d33d7cccc8f9b4e to your computer and use it in GitHub Desktop.
Parsing parallel arrays of the Wikipedia API with Codable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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