Day 39 of 100 Days Of SwiftUI

sanmiade

Oluwasanmi Aderibigbe

Posted on April 22, 2021

Day 39 of 100 Days Of SwiftUI

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)
}
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
sanmiade
Oluwasanmi Aderibigbe

Posted on April 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Go from one screen to another in SwiftUI
100daysofcode Go from one screen to another in SwiftUI

March 27, 2023

model show on click in swiftUI
100daysofcode model show on click in swiftUI

March 24, 2023

confirmationDialog() in swiftUI
100daysofcode confirmationDialog() in swiftUI

March 24, 2023

Item delete & Move in SwiftUI
100daysofcode Item delete & Move in SwiftUI

March 24, 2023