Day 39 of 100 Days Of SwiftUI
Oluwasanmi Aderibigbe
Posted on April 22, 2021
I just completed day 39 of 100 days of SwiftUI. Today I learnt about navigation links and also how to parse JSON using hierarchical Codables
.
Navigation links are used in Swift to show new screens. You can also use the sheet modifier to show a new screen but the sheet modifier is more suited to showing unrelated content like settings while navigation links should be used for showing details about a user's selection.
The Codable
protocol is used to turn JSON into Swift objects. It works fine for simple JSON structures. But for more complicated ones you will have to help Swift out.
let input = """
{
"name": "Sanmi",
"about": {
"level": "9001",
"occupation": "Android Developer"
}
}
"""
struct User: Codable {
var name: String
var about: About
}
struct About: Codable {
var level: String
var occupation: String
}
let data = Data(input.utf8)
let decoder = JSONDecoder()
if let user = try? decoder.decode(User.self, from: data) {
print(user)
}
This code converts a JSON string to a Swift object. It's actually pretty simple. All you have to do is create structs that match the JSON
Posted on April 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.