Swift ui macos @Published nil 或 Int

Swift ui macos @Published nil or Int

我有以下变量,我希望它以 nil 作为初始值,然后是 Int 值。

@Published var status: Int = 0

为了更好地理解放置所有参考代码:

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()
    }
}

使用:

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

将其设为可选(使用以下所有更正代替用法)

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

更新: 视图中可能的用法变体

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

但可能更合适(因为显示未知状态字段没有意义)

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