'SwiftUI: Why does this Boolean not change its value?

I try to change a binding bool in this function. Printing works as expected (so the transaction information is displayed correctly in the console), but the bool value - so the value of the var successfulPayment - isn't changing. I also tried to print the value of this bool after the print of "Payment was successful", but it was always false.

Note: the payment really is successful!

struct CheckView: View {

@Binding var successfulPayment: Bool

func getTransactionInformation () {

    guard let url = URL(string: "URL-HERE") else {return}

    URLSession.shared.dataTask(with: url){ [self] data, _, _ in
        let transactioninformation = try! JSONDecoder().decode(IDValues.TransactionInformation.self, from: data!)

        print(transactioninformation)

        if (transactioninformation.id == transactionId && transactioninformation.statuscode == "Success") {
            
            successfulPayment = true
            
            print("Payment was successful!")
            
        } else {
            
            }

    }
    .resume()
    
}

}

I am pretty new to coding - what am I missing here?



Solution 1:[1]

Why do you put the session in an own struct: View which isn't really a view.
You can pass the binding to the func directly (wherever you prefer it to be). Here is an example:

struct ContentView: View {
    
    @State private var successfulPayment: Bool = false
    
    var body: some View {
        Form {
            Text("Payment is \(successfulPayment ? "successful" : "pending")")
            Button("Pay") {
                getTransactionInformation($successfulPayment)
            }
        }
    }
    
    func getTransactionInformation (_ success: Binding<Bool>) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            success.wrappedValue = true
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChrisR