Swift错误 - Thread1:EXC_BAD_INSTRUCTION

时间:2017-11-09 22:39:07

标签: ios swift exc-bad-instruction

我在Xcode 9中运行代码后得到一个Thread1:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码= 0x0)。代码在Xcode 8中正常工作。

 class func loadDataFromURL(_ url: URL, completion:@escaping (_ data: Data?, _ error: NSError?) -> Void) {
    let session = URLSession.shared

    // Use NSURLSession to get data from an NSURL
    let loadDataTask = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
        if let responseError = error {
            completion(nil, responseError)
        } else if let httpResponse = response as? HTTPURLResponse {
            if httpResponse.statusCode != 200 {
                let statusError = NSError(domain:"Domain", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
                completion(nil, statusError)
            } else {
                completion(data, nil)
            }
        }
    } as! (Data?, URLResponse?, Error?) -> Void)  //Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)

    loadDataTask.resume()
}

我正在尝试从网址加载数据,我不知道为什么会收到此错误。谢谢。

1 个答案:

答案 0 :(得分:1)

不要强制转换,只需使用正确的语法,闭包中没有类型注释,最后没有类型转换:

let loadDataTask = session.dataTask(with: url, completionHandler: { (data, response, error) in
    // code
})