returning variables in a function swift

Viewed 37

I will make a Login and the post request is in the function. In the if statement if dict!["Authorized"] as AnyObject? === true as AnyObject i would like to return if the Authorization is true. But the error when want to return is Unexpected non-void return value in void function I tried to declare the func as an Bool or any other statement like this -> Bool. But that doesen't work. Here is my code.

func Login(Benutzer: String, Password: String) {


        var request = URLRequest(url: URL(string: "http://mydomain/ajax/login.php")!)
            request.httpMethod = "POST"
        let postString = "Benutzername=\(String(describing: Benutzer))&Password=\(String(describing: Password))"
            request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                  // check for fundamental networking error
            print("error=\(String(describing: error))")
            DispatchQueue.main.async {
        if error as AnyObject? === "The Internet is Down" as AnyObject {
            }
        else {
        let alert = UIAlertController(title: "Error", message: "You have to turn on your Internet or Server is Down ", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true)
            }

                }
                    return
                }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
                                }

            let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(String(describing: responseString))")

        func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                        }
                            }
                               return nil
                           }

        let dict = convertToDictionary(text: responseString!)
            DispatchQueue.main.async {
                if dict!["Authorized"] as AnyObject? === true as AnyObject {

                    return true
                    // error is here

                }

            else {


                let alert = UIAlertController(title: "Error", message: dict!["Message"] as? String, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    self.present(alert, animated: true)
                        }
                    }
                }
                task.resume()

    }



    @IBAction func loginTapped(_ sender: Any) {

        let Benutzer = benutzernameTextField.text;
        let Password = passwordTextField.text;

        if benutzernameTextField.text == Benutzer && passwordTextField.text == Password {


        }
    }
}
1 Answers

The issue is that at one point in the function you have just return and at another point in the function you have return true. Swift is strongly typed and a function always has to return the same type - you can't return a bool in one case and nothing in another. What you probably want to do is change the first return to return false and then add -> Bool to the function's signature. Another option would be to return an optional bool (-> Bool?) and return nil in the first case. Also, as a side note, you probably want to lowercase the "L" in "Login" - that's just convention.

func Login(Benutzer: String, Password: String) -> Bool {


        var request = URLRequest(url: URL(string: "http://mydomain/ajax/login.php")!)
            request.httpMethod = "POST"
        let postString = "Benutzername=\(String(describing: Benutzer))&Password=\(String(describing: Password))"
            request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                  // check for fundamental networking error
            print("error=\(String(describing: error))")
            DispatchQueue.main.async {
        if error as AnyObject? === "The Internet is Down" as AnyObject {
            }
        else {
        let alert = UIAlertController(title: "Error", message: "You have to turn on your Internet or Server is Down ", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true)
            }

                }
                    return false
                }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
                                }

            let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(String(describing: responseString))")

        func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                        }
                            }
                               return nil
                           }

        let dict = convertToDictionary(text: responseString!)
            DispatchQueue.main.async {
                if dict!["Authorized"] as AnyObject? === true as AnyObject {

                    return true

                }

            else {


                let alert = UIAlertController(title: "Error", message: dict!["Message"] as? String, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    self.present(alert, animated: true)
                        }
                    }
                }
                task.resume()

    }



    @IBAction func loginTapped(_ sender: Any) {

        let Benutzer = benutzernameTextField.text;
        let Password = passwordTextField.text;

        if benutzernameTextField.text == Benutzer && passwordTextField.text == Password {


        }
    }
}
Related