Search code examples
swiftalamofire

What is causing this "Cannot convert type" error in Swift?


I want to call a simple api and return the struct of JSON returned from server. I am using alamofire to achieve this.

This is my function

func loginUser(user_name: String, password: String, callBack:(Login) -> Void){
    let parameters: Parameters = ["user_name":  user_name,"password": password];
    let urlString=serverURL+"login.php";
    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
        .responseJSON { response in
            if let status = response.response?.statusCode {
                switch(status) {
                case 200:
                    guard response.result.isSuccess else {
                        //error handling
                        return
                    }
                    if let login: Login = response.result.value {
                        callBack(login)
                    } else {
                        callBack(Login(user_id: 0, status:0))
                    }
                default:
                    print("HTTP Error : \(status)")
                    callBack(Login(user_id: 0, status:0))
                }
            }
    }
}

struct Login {
  let user_id: Int
  let status: Int
}

This line is generating a "cannot convert type" error.

if let login: Login = response.result.value {

What am I doing wrong?


Solution

  • As mag_zbc commented response.result.value is either [String : Any] or Array.

    So first you need to cast them to respective type like suppose it's [String : Any] you can cast it as shown below:

    if let response = response.result.value as? [String : Any] {
        //here you will get your dictionary
    }
    

    Now next thing you need to do is you need to take out the values from your response object which you can do by accessing the values from the keys from your response object which will look like:

    let user_id = response["userid_key"] as? Int ?? 0
    let status = response["status_key"] as? Int ?? 0
    

    This way you will get user_id and status from your response object and then last step will be to set that data into your struct like shown below:

    let login = Login(user_id: user_id, status: status)
    

    Now you can set your callback with callBack(login)

    and your final code will look like:

    if let response = response.result.value as? [String : Any] {
    
        let user_id = response["userid_key"] as? Int ?? 0
        let status = response["status_key"] as? Int ?? 0
    
        let login = Login(user_id: user_id, status: status)
    
        callBack(login)
    }