Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Last active October 21, 2023 13:13
Show Gist options
  • Save StewartLynch/0f9edf5bf5b0a149b2059494401fb36d to your computer and use it in GitHub Desktop.
Save StewartLynch/0f9edf5bf5b0a149b2059494401fb36d to your computer and use it in GitHub Desktop.
A JSON Parsing example for the dictionary api
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")
@Renat3000
Copy link

Renat3000 commented Oct 20, 2023

hey! I just want to thank you for this bit!
I was facing one problem, was trying to decode json from the same api, but had an error:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

I changed Post.self to [Post].self, cause we need to pass an array type to JSONDecoder.decode and it works now! Thank you very much 🙌🏻🙏🏻

@StewartLynch
Copy link
Author

StewartLynch commented Oct 20, 2023 via email

@Renat3000
Copy link

I am curious. How did you find it?

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment