使用Result <t>调用函数

时间:2018-05-07 08:10:43

标签: swift

我有这段代码:

enum Result<T> {
        case succes(T)
        case error(String)
    }    
typealias completionHandler = (Result<Data >) -> ()
        func getJsonFromServer(parameters: String, completion: @escaping completionHandler) {
        let fullUrlString = ApiConstans.fullPath + parameters
        guard let url = URL(string: fullUrlString) else {
            return completion(.error("Error 100: Problem with url"))
        }

    URLSession.shared.dataTask(with: url) {  (data, response, error) in
        guard error == nil else {
            return completion(.error("Error 101: Problem with data"))
        }

        guard let data = data else {
            return completion(.error("Error 102: Problem with data"))
        }

        debugPrint("R> \(fullUrlString)")
        return completion(.succes(data))
    }.resume()
}

    func checkUsersLogin(login: String?, password: String?, completion: @escaping completionHandler) {
        self.getJsonFromServer(parameters: "?action=LOGOWANIE&login=\(login!)&password=\(password!)", completion: completion)
    }

我怎么称呼它?

我试试这个:

@IBAction func btnLoginPressed(_ sender: Any) {
        if self.textFieldLogin.text?.isEmpty ?? true || self.textFieldPassword.text?.isEmpty ?? true  {
            self.errorLoginMessage(txt: "Error", title: "Error")
        } else {
            cms.checkUsersLogin(login: self.textFieldLogin.text, password: self.textFieldPassword.text, completion: { (data) in
                if data.error == nil, let data = data {
                    do {
                        let decoder = JSONDecoder()
                        loggedUser = try decoder.decode(LoginUser.self, from: data)

                        if ((loggedUser?.id ) == nil) {
                            let jsonValues = try? JSONSerialization.jsonObject(with: data, options: [])
                            if let downloadJson = jsonValues as? [String: Any], let message = downloadJson["komunikat"] as? String, let title = downloadJson["error"] as? String {
                                DispatchQueue.main.async {
                                    self.errorLoginMessage(txt: message, title: title)
                                }
                            } else {
                                DispatchQueue.main.async {
                                    self.errorLoginMessage(txt: "Podany login lub hasło jest błędny!!", title: "Błąd")
                                }
                            }
                        } else {
                            DispatchQueue.main.async {
                                dump(loggedUser)
                                self.performSegue(withIdentifier: "toLoginUser", sender: self)
                            }
                        }
                    }
                    catch {
                        print("Error in decoder")
                    }

                } else {
                    print("Error 104: \(error)")
                }


            })
        }
    } 

但我有错误: 枚举元素&#39;错误&#39;不能作为实例成员引用:如果data.error == nil,则让data = data {

使用未解析的标识符&#39;错误&#39;:print(&#34;错误104 :(错误)&#34;)

我可以请你修复这段代码吗?

3 个答案:

答案 0 :(得分:1)

更改您的代码,如:

@IBAction func btnLoginPressed(_ sender: Any) {
    if self.textFieldLogin.text?.isEmpty ?? true || self.textFieldPassword.text?.isEmpty ?? true  {
        self.errorLoginMessage(txt: "Error", title: "Error")
    } else {
        cms.checkUsersLogin(login: self.textFieldLogin.text, password: self.textFieldPassword.text, completion: { (data) in

            switch(data) {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    loggedUser = try decoder.decode(LoginUser.self, from: data)

                    if ((loggedUser?.id ) == nil) {
                        let jsonValues = try? JSONSerialization.jsonObject(with: data, options: [])
                        if let downloadJson = jsonValues as? [String: Any], let message = downloadJson["komunikat"] as? String, let title = downloadJson["error"] as? String {
                            DispatchQueue.main.async {
                                self.errorLoginMessage(txt: message, title: title)
                            }
                        } else {
                            DispatchQueue.main.async {
                                self.errorLoginMessage(txt: "Podany login lub hasło jest błędny!!", title: "Błąd")
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            dump(loggedUser)
                            self.performSegue(withIdentifier: "toLoginUser", sender: self)
                        }
                    }
                }
                catch {
                    print("Error in decoder")
                }
            case .error(let error):
                print("Error 104: \(error)")
            }

        })
    }
}

答案 1 :(得分:0)

试试这个:

@IBAction func btnLoginPressed(_ sender: Any) {
            if self.textFieldLogin.text?.isEmpty ?? true || self.textFieldPassword.text?.isEmpty ?? true  {
                self.errorLoginMessage(txt: "Error", title: "Error")
            } else {
                cms.checkUsersLogin(login: self.textFieldLogin.text, password: self.textFieldPassword.text, completion: { (data) in

                    switch data {
                    case .error(let error):
                        print(error)
                    case .success(let data):
                        do {
                            let decoder = JSONDecoder()
                            loggedUser = try decoder.decode(LoginUser.self, from: data)

                            if ((loggedUser?.id ) == nil) {
                                let jsonValues = try? JSONSerialization.jsonObject(with: data, options: [])
                                if let downloadJson = jsonValues as? [String: Any], let message = downloadJson["komunikat"] as? String, let title = downloadJson["error"] as? String {
                                    DispatchQueue.main.async {
                                        self.errorLoginMessage(txt: message, title: title)
                                    }
                                } else {
                                    DispatchQueue.main.async {
                                        self.errorLoginMessage(txt: "Podany login lub hasło jest błędny!!", title: "Błąd")
                                    }
                                }
                            } else {
                                DispatchQueue.main.async {
                                    dump(loggedUser)
                                    self.performSegue(withIdentifier: "toLoginUser", sender: self)
                                }
                            }
                        }
                        catch {
                            print("Error in decoder")
                        }
                    }
                })
            }
        }

答案 2 :(得分:0)

检查变量是否为特定的枚举值:

if case let Result.error(error) = data {
    // do something with error
}