Swift 错误 - 线程 1:EXC_BAD_INSTRUCTION

Swift Error - Thread1: EXC_BAD_INSTRUCTION

我在 Xcode 9 中的 运行 我的代码之后得到一个线程 1:EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=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()
}

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

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

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