将字符串添加到错误枚举以传递给控制器

Adding String to error enumeration to pass to controllers

在用户登录服务器的过程中,我为错误定义了一个枚举

enum loginError: Error {
    case networkError
    case authorization
    case emptyUsernameOrPassword
}

并且在模型中,我在 completion 部分添加了这些错误。并将此错误发送到控制器。 例如这里:

mutating func loginUser(completion: @escaping (Result<String,loginError>) -> Void ) {
    let urlString = loginUrl
    guard let url = URL(string: urlString) else {fatalError()}

    let body: [String: Any] = [
        "username" : username,
        "password" : password,
        "client" : "time_tracker_chrome_extension",
        "device" : "iPhone",
        "device_type" : "Phone"
    ]


    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = body.percentEscaped().data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            //Check the response from the server
            if let response = response as? HTTPURLResponse {
                print("statusCode: \(response.statusCode)")
            }

            guard let json = try? JSONDecoder().decode(Response.self, from: data!) else {

                 //Here........
                completion(.failure(loginError.authorization))
                return
            }

如何将这些错误转换为 String,然后将此错误的 String 发送给控制器。

它是这个的控制器

@IBAction func pressLoginBtn(_ sender: UIButton) {
    guard usernameInput.hasText, passwordInput.hasText  else {return}

    let username = usernameInput?.text
    let password = passwordInput?.text
    var login = LogginReguest(username: username!, password: password!)

    login.loginUser { result in
        switch result {
        case .success(let string):
            print(string)
        case .failure(let error):
            print(error)

        }
    }
}

您并没有真正转换错误,但您需要一些功能来将错误消息与每个错误相关联。下面是枚举符合 CustomStringConvertible

的示例
enum LoginError: Error, CustomStringConvertible {
    case networkError
    case authorization
    case emptyUsernameOrPassword

    var description: String {
        switch self {
        case .networkError:
            return "A network error occured"
        case .authorization:
            return "Not authorized"
        case .emptyUsernameOrPassword:
            return "Username or poassword not given"
        }
    }
}

示例

let error = LoginError.authorization
print(error)

打印

Not authorized

但您也可以在控制器中 switch class 或作为单独的功能实现。