UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 99 SnowSeeker Challenge 2

Forums > 100 Days of SwiftUI

Hi guys, i have a question on how to load the saved data for favorite ski resort.

Here is my take on the loading init but i am stuck at the input for the Decodable.Protocol since it won't allow me to use 'resort' of type Set of string

class Favorites: ObservableObject {

    private var resorts: Set<String>

    private let saveKey = "Favorite"

    init() {

        if let data = UserDefaults.standard.data(forKey: saveKey) {
            if let decoded = try? JSONDecoder().decode(<#T##type: Decodable.Protocol#>, from: data) {
                self.resorts = decoded
                return
            }
        }

2      

JSON doesn't do sets, so decode it as an array and assign it to resorts with .init(decoded)

Although...

Set conforms to Decodable if its Element is Decodable so this should work:

        if let data = UserDefaults.standard.data(forKey: saveKey) {
            if let decoded = try? JSONDecoder().decode(Set<String>.self, from: data) {
                self.resorts = decoded
                return
            }
        }

I tried similar code in a playground and it worked just fine.

3      

many thanks @roosterboy. The second method works perfect for me but i would like to know more about the 1st one as well. Is it possible for you to provide me with the syntax on how to decode a set as an array and assigning it to resort. I would love to get my hand on a general approach so that i would know how to handle it in the later stage.

2      

Sure, you would just do it like this:

        if let data = UserDefaults.standard.data(forKey: saveKey) {
            if let decoded = try? JSONDecoder().decode([String].self, from: data) {
                self.resorts = .init(decoded)
                return
            }
        }

3      

Thanks!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.