在结构的计算属性内访问环境对象属性

时间:2020-04-18 19:44:02

标签: swift swiftui combine

我目前有一个结构,该结构具有一个称为“ answerArray”的计算属性。我想将此值数组与另一个存储在Environment对象中的值数组进行比较。

struct CandidateModel {
@EnvironmentObject var model: CardViewModel

let index: Int
var name: String
var answers: [AnswerModel]
var answerArray: [Double] {
    get {
        var arr: [Double] = []
        for i in answers {
            if i.isKeyIssue {
            // If answer is a key issue
                arr.append(i.score * 1.5)
                // Apply multiplier and append to answer array
            }
            else {arr.append(i.score)}
            // otherwise just append to list
        }
        return arr
    }
}
var scoreArray: [Double] {
    get {

        var compScoreArray: [Double] = []

        for i in 0...self.model.getAnswerList().count - 1 {
            let questionDifference = abs(self.answerArray[i] - self.model.answerList[i])
            compScoreArray.append(questionDifference)
        }

        return compScoreArray
    }
}

当我尝试访问此属性时,出现以下错误:

Thread 1: Fatal error: No ObservableObject of type CardViewModel found. A View.environmentObject(_:) for CardViewModel may be missing as an ancestor of this view.

当环境对象中的answerList属性更改时,我只是尝试更新CandidateModel中的scoreArray属性。我怎样才能更好地实现这一目标?

这是我的查看代码:

struct SentimentComparisonBarView: View {
@EnvironmentObject var model: CardViewModel

var body: some View {
    HStack {
      // 2
        Image("Jobs_Economy")
            .renderingMode(.template)
            .resizable()
            .scaledToFit()
            .frame(width: 50)
            .foregroundColor(Color.init(#colorLiteral(red: 0.3942148186, green: 0.3146163453, blue: 0.4587302703, alpha: 1)))

        Text("Jobs/Economy")
            .frame(width: 120, alignment: .leading)
          // 3
          Rectangle()
            .fill(Color.init(#colorLiteral(red: 0.5201314092, green: 0.3027745485, blue: 0.49252671, alpha: 1)))
            .frame(width: CGFloat(2 * 10.0), height: 5.0)
          // 4
          Spacer()
            Text("Low")
                .padding(.horizontal, 10)

        Button("Test") {
            print(self.model.presidentialCandidates[0].scoreArray)
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您应该在视图中使用@EnvironmentObject并将其传递给模型。并且不要忘记调用.environmentObject,将CardViewModel注入SceneDelegate中。例如:

let myView = MyView().environmentObject(CardViewModel())