这个函数中返回的元组有什么问题?

时间:2014-12-12 03:06:51

标签: ios swift tuples

这是一个假定返回类型为Int和Dictionary<的元组的函数。 String,AnyObject>但是我一直得到这个错误“元组类型”(Int,Dictionary< String,AnyObject>)'和'(''有不同数量的元素(2对0)。“这很奇怪,因为它似乎告诉我,我正在返回正确的元组,但我不确定为什么它说“(元组)和'()'”有不同的论点。

    class func SomeFunc(param: String) -> (x: Int, y: Dictionary<String, AnyObject>){

    var request = HTTPTask()
    request.responseSerializer = JSONResponseSerializer()

    let params: Dictionary<String,AnyObject> = ["key": param]
    request.POST("http://mysite/url", parameters: params, success: {(response: HTTPResponse) in

        let dict = response.responseObject as Dictionary<String,AnyObject>
        let status:Int = 200
        return (status, dict) //Tuple types '(Int, Dictionary<String, AnyObject>)' and '()' have a different number of elements (2 vs. 0)


        },failure: {(error: NSError, response: HTTPResponse?) in

    })

}

1 个答案:

答案 0 :(得分:1)

传入一个闭包并使用所需的参数执行它:

func SomeFunc(param: String, withCompletion completion: (x: Int, y: Dictionary<String, AnyObject>) -> ()) {

    var request = HTTPTask()
    request.responseSerializer = JSONResponseSerializer()

    let params: Dictionary<String,AnyObject> = ["key": param]
    request.POST("http://mysite/url", parameters: params, success: {(response: HTTPResponse) in

        let dict = response.responseObject as Dictionary<String,AnyObject>
        let status:Int = 200
        completion(x: status,y: dict) //Tuple types '(Int, Dictionary<String, AnyObject>)' and '()' have a different number of elements (2 vs. 0)


        },failure: {(error: NSError, response: HTTPResponse?) in

    })