Last active
October 21, 2023 13:13
-
-
Save StewartLynch/0f9edf5bf5b0a149b2059494401fb36d to your computer and use it in GitHub Desktop.
A JSON Parsing example for the dictionary api
This file contains 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 UIKit | |
struct Post: Decodable { | |
let word: String | |
let meanings:[Meanings] | |
struct Meanings: Decodable { | |
let partOfSpeech: String? | |
let definitions: [Definitions] | |
} | |
struct Definitions: Decodable { | |
let definition: String | |
let example: String? | |
} | |
} | |
func getWord(_ wordString: String) { | |
var urlString = "https://api.dictionaryapi.dev/api/v2/entries/en/\(wordString)" | |
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! | |
print(urlString) | |
guard let url = URL(string:urlString) else { | |
return | |
} | |
let request = URLRequest(url: url) | |
URLSession.shared.dataTask(with: request) { data, response, error in | |
if let error = error { | |
print(error.localizedDescription) | |
return | |
} | |
guard let data = data else { | |
return | |
} | |
let decoder = JSONDecoder() | |
guard let posts = try? decoder.decode([Post].self, from: data) else { | |
print("Could not decode") | |
return } | |
for post in posts { | |
print("Word: \(post.word)") | |
print("Definitions:") | |
for meaning in post.meanings { | |
for definition in meaning.definitions { | |
print("• \(definition.definition)") | |
if let example = definition.example { | |
print("Example: \(example)") | |
} | |
} | |
} | |
} | |
}.resume() | |
} | |
getWord("search") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
well, given my little experience with APIs I haven't seen the APIs which have an array at the very first "level" and I thought "that's strange, maybe if I google how to decode this particular api.dictionaryapi.dev/api/v2 I will find some solution" and here I am!