TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Question regarding iExpense

Forums > 100 Days of SwiftUI

I have a few doubts that popped up in this project. Here's the code.

class Expenses: ObservableObject {
    @Published var items = [ExpenseItem]() {
          didSet {
            if let data = try? JSONEncoder().encode(items) {
                UserDefaults.standard.set(data, forKey: "Items")
            }
        }
    }

    init() {
        if let savedItems = UserDefaults.standard.data(forKey: "Items") {
            if let decodedItems = try? JSONDecoder().decode([ExpenseItem].self, from: savedItems) { //i dont know whats [EspenseItem].self

                items = decodedItems
                return
            }
        }
        items = [] //Huh? whats this?
    }
}

The commented parts explain what i dont understand. Thank you for reading. Funny thing is that i actually had 4-5 questions but while writing the comments the solution came to me. So. only 2 things that i dont understand.

2      

@Bnerd  

Read it as below:

init() {
        if let savedItems = UserDefaults.standard.data(forKey: "Items") {
            if let decodedItems = try? JSONDecoder().decode([ExpenseItem].self, from: savedItems) { //i dont know whats [EspenseItem].self

                items = decodedItems
                return
            }
        } else {
          items = []
        }

    }

In other words, if the loading fails, just return an empty Array.

3      

Thanks @Bnerd! 1 more thing left if you have time & know it.whats [ExpenseItem].self?

2      

@Bnerd  

ExpenseItem is the struct you made to store your expenses. .self = (if I am not mistaken) means that you refer to the ExpenseItem Struct itself and not an new instance of it. Found the below which is a good read to understand the "self" have a quick look to get a better idea. https://www.codingem.com/self-in-swift/

2      

Thanks!

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.