SwiftUI 设置将触发视图刷新的外部变量

SwiftUI setting up external variables that will trigger a view refresh

iOS13,Swift5,Xcode11.3.1

学习SwiftUI。我把它放在一起,它起作用了,但是它是正确的吗?

External.swift

class BlobModel: ObservableObject {
  @Published var score: String = "" 
}

var globalBlob = BlobModel()

ContentView.swift

struct ContentView: View {

@ObservedObject var globalBlob:BlobModel

var body: some View {
  Text("\(globalBlob.score)")
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
      ContentView(globalBlob: globalBlob)
    }
}

当我在 External.swift 中写入 globalBlob 时,它会更新显示。

globalBlob.score = backToString

但是 globalBlob 是一个全局变量,这肯定是糟糕的编码习惯。我应该有更好的方法吗?

你能从改变分数的 class 访问单例实例吗? https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton

struct ContentView: View {

    @ObservedObject var globalBlob: BlobModel = BlobModel.sharedInstance

    var body: some View {
        VStack{
            Button(action: {self.globalBlob.score = Int.random(in: 0...100).description}, label: {Text("update-score")})
            Text("\(globalBlob.score)")
        }
    }

}

class BlobModel: ObservableObject {
    static let sharedInstance = BlobModel()
    @Published var score: String = ""
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}