关闭downcast导致EXC_BAD_INSTRUCTION错误

时间:2016-05-14 18:04:23

标签: ios swift2 alamofire

在我正在写一篇与WeatherUnderground合作的课程中,我需要一些与这个函数几乎完全相同的函数,这个函数在这个形式下工作正常:

func currentConditions(completion: (result: WUConditionResponse?) -> Void) -> Request {
    url = urlBuilder("conditions")
    let request = Alamofire.request(.GET, url)
        .validate()
        .responseObject { (response: Result<WUConditionResponse, NSError>) in
            completion(result: response.value)
    }
    return request
}

我没有单独写下它们,而是尝试了这个:

private typealias AFCompletion = (result: EVObject?) -> Void
private func current(command: String, onCompletion: AFCompletion) -> Request {
    let function = {(completion: AFCompletion) -> Request in
        self.url = self.urlBuilder(command)
        let request = Alamofire.request(.GET, self.url)
            .validate()
            .responseObject { (response: Result<EVObject, NSError>) in
                completion(result: response.value!)
        }
        return request
    }
    return function(onCompletion)
}

其次是

func currentConditions(completion: (result: WUConditionResponse?) -> Void) -> Request {
    let myCompletion = completion as! AFCompletion
    return current("conditions", onCompletion: myCompletion)
}

其中WUConditionResponseEVObject的子类。然后我使用带有语句的构造,与正在工作的内容保持不变:

    foo.currentConditions { (conditions: WUConditionResponse?) in
        print(conditions)
    }

通过这种方式,我在向下转发AFCompletion时出现EXC_BAD_INSTRUCTION错误。我无法看到问题所在。为什么垂头丧气?尽管有完整的答案,我如何进一步调试?

1 个答案:

答案 0 :(得分:1)

你尝试这样做的方式是不可能的。你传递的关闭

foo.currentConditions { (conditions: WUConditionResponse?) in
    print(conditions)
}

仅接受 WUConditionResponseEVObject的一个特定子类。如果将该闭包转换为AFCompletion,则生成的闭包必须接受 每个 EVObject,而不是

如果实际传入的对象类型正确而不是强制转换,那么 可以做的只是创建第二个调用completion

func currentConditions(completion: (result: WUConditionResponse?) -> Void) -> Request {
    let myCompletion : AFCompletion = { res in 
        if res != nil || res! is WUConditionResponse {
             return completion(res as! WUConditionResponse?)
        }
        return false // default return
    }
    return current("conditions", onCompletion: myCompletion)
}