Swift UI MacOS @已发布nil或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 

更新: View中用法的可能变体

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章