Paul
Paul

Reputation: 4460

Swift ui macos @Published nil or Int

I have the following variable, I would like it to take nil as an initial value and then an Int value.

@Published var status: Int = 0

To better understand place all the reference code:

struct ServerMessage: Decodable {
    let token: String
}

class Http: ObservableObject {
    @Published var status: Int = 0
    @Published var authenticated = false
    func req(url: String, httpMethod: String, body: [String: String]?) {
        guard let url = URL(string: url) else { return }
        let httpBody = try! JSONSerialization.data(withJSONObject: body ?? [])
        var request = URLRequest(url: url)
        request.httpMethod = httpMethod
        request.httpBody = httpBody
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        URLSession.shared.dataTask(with: request) { data, response, error in
            if error != nil {
                print("Error: \(String(describing: error))")
                return
            }
            
            if let httpResponse = response as? HTTPURLResponse {
                switch httpResponse.statusCode {
                case 400: do {
                    print("Error: 400")
                    DispatchQueue.main.async {
                        self.status = 400
                    }
                    return
                    }
                case 401: do {
                    print("Error: 401")
                    DispatchQueue.main.async {
                        self.status = 401
                    }
                    return
                    }
                default: do {}
                }
            }
            
            do {
                if let data = data {
                    let results = try JSONDecoder().decode(ServerMessage.self, from: data)
                    DispatchQueue.main.async {
                        self.authenticated = true
                    }
                    print("Ok.", results)
                } else {
                    print("No data.")
                }
            } catch {
                print("Error:", error)
            }
        }.resume()
    }
}

Use:

self.http.req(
            url: "",
            httpMethod: "POST",
            body: ["email": "", "password": ""]
        )

Upvotes: 2

Views: 1140

Answers (1)

Asperi
Asperi

Reputation: 258345

Make it optional (with all following corrections in place of usage)

@Published var status: Int? = nil     // << I like explicit initialising 

Update: possible variant of usage in View

Text("\(http.status ?? 0)")    // << it is Int, so ?? "" is not valid

but probably it is more appropriate (due to no sense to show unknown status field)

if http.status != nil {
   Text("\(http.status!)")
}

Upvotes: 2

Related Questions