SwiftUI未知属性“可观察对象”

时间:2019-10-14 21:30:05

标签: swiftui

因此,我在下面的ObservableObject调用旁边收到错误未知属性@ObservableObject var dataSource = DataSource()ObservableObject几天前在另一个项目中运行良好,但现在已经不行了。

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)
            }
        } 
    } 
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

ObservableObjectObservedObject必须遵守的协议。有关ObservableObject的文档,请参见here;有关ObservedObject的文档,请参见hereContentView是您要查找的属性包装器。将您的struct ContentView: View { @ObservedObject var dataSource = DataSource() var body: some View { VStack { Text("Expenses") List(dataSource.expenses) { expense in ExpenseRow(expense: expense) } } } } 代码更改为此:

sqlsrv