在我正在编写与WeatherUnderground一起使用的 class 中,我需要一些几乎与此功能完全相同的函数,在这种形式下,它们可以正常工作:

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错误。我茫然看到这个问题。为什么向下转换失败?尽管有完整的答案,我该如何进一步调试呢?

最佳答案

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

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

仅接受,即WUConditionResponse的一个特定子类 EVObject。如果将该闭包转换为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)
}

10-08 02:42