gpt4 book ai didi

ios - 关闭向下转换导致 EXC_BAD_INSTRUCTION 错误

转载 作者:行者123 更新时间:2023-11-29 12:00:30 24 4
gpt4 key购买 nike

在我编写的与 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 错误。我不知所措地看到了这个问题。为什么会出现 downcast 错误?尽管有完整的答案,我该如何进一步调试?

最佳答案

按照您尝试的方式,这是不可能的。你传入的闭包

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

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

可以做的是创建第二个调用完成如果实际传入的对象是正确的类型而不是转换:

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)
}

关于ios - 关闭向下转换导致 EXC_BAD_INSTRUCTION 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com