【问题标题】:Swift ui macos @Published nil or IntSwift ui macos @Published nil 或 Int
【发布时间】:2020-08-27 09:24:15
【问题描述】:

我有以下变量,我希望它以 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": ""]
        )

【问题讨论】:

    标签: swift null swiftui integer


    【解决方案1】:

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

    @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!)")
    }
    

    【讨论】:

    • 我尝试过类似的方法,问题是当我这样使用它时: Text ("\ (http.status)") Error: Instance method 'appendInterpolation' requires that 'Int?'符合'_FormatSpecifiable'
    • 它甚至不能像这样工作:Text ("\ (http.status ??" ")") 或 Text ("\ (http.$status ??" ")")
    • 最后一个例子似乎工作了这一点!在 http.status 上?
    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2023-04-09
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多