简体   繁体   中英

SWIFT IOS return 2 different objects in a same function

I want to return request if all went well and return error if something went wrong.

func afnwPost(url: String,client_id: String, client_secret:String,grant_type:String, userparam: String, passwordparam:String)-> AnyObject{

    var parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":grant_type,"username":userparam,"password":passwordparam]

    manager.POST( url,
    parameters: parameters,
    success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
    println("JSON: " + responseObject.description)
    return responseObject
    },
    failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
    println("Error: " + error.localizedDescription)
    return error
    })
}

The call method

 var respuesta = obtenerToken.afnwPost(host_oauth,
        client_id: client_id,
        client_secret:client_secret,
        grant_type:grant_type_token,
        userparam: textfieldUsuario.text,
        passwordparam: textfieldContrasenya.text)

You can return two different objects by using a Tuple like that:

//Dummy method to show how it works.
func yourFunction()->(responseObject:AnyObject, error:String){
  return (responseObject, error)
}

To access them again, do something like that:

var yourResult = yourFunction()
println(yourResult.responseObject)
println(yourResult.error)

Of course you will have to check, which value is nil when you receive the returns of your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM