Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Unknown Attribute 'Observable Object'

Tags:

swiftui

So I'm getting the error Unknown attribute ObservableObject next to the @ObservableObject var dataSource = DataSource() call below. the ObservableObject worked perfectly a couple days ago in another project but not anymore.

import SwiftUI
import Combine


class DataSource: ObservableObject {

    var willChange = PassthroughSubject<Void,Never>()


    var expenses = [Expense]() {
        willSet { willChange.send() }
    }
    var savingsItems = [SavingsItem](){
        willSet { willChange.send() }
    }

    //@State var monthlyIncomeText: String
    //var monthlyIncome: Int = 1364


    init(){
        addNewExpense(withName: "Spotify", price: 14)

    }

    func addNewExpense(withName name: String, price: Int){
        let newExpense = Expense(name: name, price: price)
        expenses.append(newExpense)
    }

     func addNewSavingsItem(withName name: String, price: Int, percentage: Double){
        let newSavingsItem = SavingsItem(name: name, price: price, timeTilCompletion: 0, percentage: percentage)
        savingsItems.append(newSavingsItem)
    }
}

struct ContentView: View {

    @ObservableObject var dataSource = DataSource()

    var body: some View {
        VStack{
            Text("Expenses")
            List(dataSource.expenses) { expense in
                ExpenseRow(expense: expense)
            }
        } 
    } 
}

Could anyone help?

like image 356
Mikael Wills Avatar asked Oct 14 '19 21:10

Mikael Wills


People also ask

What is an observable object SwiftUI?

A type of object with a publisher that emits before the object has changed.

What is Observedobject?

A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.

How can an observable object announce changes to SwiftUI?

ObservableObject will automatically synthesize the objectWillChange property. Each SwiftUI view that uses your ObservableObject will subscribe to the objectWillChange changes. Now, if your model changes one of the @Published variables, then SwiftUI will redraw all of the views that use your ObservableObject.


1 Answers

ObservableObject is a protocol that ObservedObjects must conform to. See here for documentation on ObservableObject, and here for documentation on ObservedObject, which is the property wrapper that you are looking for. Change your ContentView code to this:

struct ContentView: View {

    @ObservedObject var dataSource = DataSource()

    var body: some View {
        VStack {
            Text("Expenses")
            List(dataSource.expenses) { expense in
                ExpenseRow(expense: expense)
            }
        } 
    } 
}
like image 186
RPatel99 Avatar answered Dec 24 '22 03:12

RPatel99