我正在使用SwiftUI开发iOS应用程序,但无法显示从数据库中获取的数据。
import SwiftUI
import Firebase
import FirebaseDatabase
var ref = Database.database().reference()
class Observe {
static func currentSingleEventObserve(completion: @escaping ((String?) -> ())) {
let path = "supersonic/current"
let ref = Database.database().reference().child(path)
_ = ref.observeSingleEvent(of: .value, with: { snapshot in
let temp = (snapshot.value! as AnyObject).description
completion(temp)
})
}
}
struct CurrentDistance: View {
var value: NSDictionary?
var refHandle: UInt = 0
@State var distance: String
init() {
Observe.currentSingleEventObserve(completion: { temp in
self.distance = temp // I want to mutate self.distance here
})
}
var body: some View {
VStack {
Text("Distance")
Text(self.distance)
}
}
}
struct CurrentDistance_Previews: PreviewProvider {
static var previews: some View {
CurrentDistance()
}
}
|-supersonic
|- current: 30
我想在初始化器中对self.distance
进行突变。尝试在闭包中更改self.distance
时出现错误Escaping closure captures mutating 'self' parameter
,并且我不知道如何更新该值。
如何显示从数据库中获取的值?