Home > database >  Why @State property is not set?
Why @State property is not set?

Time:09-08

Local variable d2 and data has the same type, but though d2 has two key value par, it is not getting assigned to data, why? Does @State makes it specific?

struct ContentView: View {
    
    @State var data: [String: Any] = [String: Any]()
    @State var res: ValidationResult?

    init() {
        updateValue()
        return
    }
    
    func updateValue() {
        do {
            if let jsonURL = Bundle.main.url(forResource: "user", withExtension: "json") {
                let jsonData = try Data(contentsOf: jsonURL)
                guard let d2 = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as? [String: Any] else {
                    print("Can not convert to d2")
                    return
                }
                data = d2 // <-------

CodePudding user response:

@State starts it's work after the view appears so you need to remove it

var data = [String: Any]()

Or Do this structure instead

class Model:ObservableObject {
   @Published var data = "123"
   var input: [String: String] = ["name": "Janos", "address": "aaa"]
    init() {
        data = "456"
    }
}

struct ContentView: View {
    
     @ObservedObject var model = Model()
    
    var body: some View {
        Text(model.data)
            .padding()
    }
}

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