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

标签 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 错误。我不知所措地看到了这个问题。为什么会出现 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/

相关文章:

ios - 用属性字符串和文本替换正则表达式匹配

iphone - unsignedIntValue 与 intValue

ios - 在没有搜索 Controller 的情况下快速更改搜索栏中文本字段的高度

objective-c - 使用 NSCharacterSet 删除所有不需要的字符

ios - 录音看起来没问题,但播放却不行

swift - 录制和播放声音在模拟器中效果很好,但在我的 iPhone 中则不然

iOS SDK Hue Philips with Swift

swift - Alamofire 4 请求出错

ios - 无法使用 Alamofire 成功完成带有参数的 GET 请求

swift - Alamofire 类型 'ParameterEncoding' 没有成员 'URL' Swift 3