Future 和 DispatchQueue 生成构建错误

问题描述 投票:0回答:1

我正在尝试构建一个快速应用程序,并且正在打开一个 JSON 文件。由于它在主线程上可能很耗时,所以我想在后台执行它。

这是我正在使用

Future
DispatchQueue

进行的通话
func getFeed() -> Future<[ios_foodloose_app.FeedItemEntity], Error> {
        return Future<[FeedItemEntity], Error> { promise in
            
            guard let url = Bundle(for: MockedFeedService.self).url(forResource: "basic-test-feed-response",withExtension: "json"),
                  let data = try? Data(contentsOf: url) else {
                return promise(.failure(NSError(domain: "", code: 401, userInfo: [ NSLocalizedDescriptionKey: "Error"])))
            }
            
            do {
                DispatchQueue.global(qos: .background).async {
                    let response = try JSONDecoder().decode( [FeedItemEntity].self, from: data)
                    DispatchQueue.main.async {
                        promise(.success(response))
                    }
                }
            } catch {
                print("JSON Decode error: \(error)")
                promise(.failure(error))
            }
        }
            
    }

但是 Xcode 仍然在线上抱怨

DispatchQueue.global(qos: .background).async {

Invalid conversion from throwing function of type '@Sendable () throws -> Void' to non-throwing function type '@Sendable @convention(block) () -> Void'

知道如何解决吗?

谢谢

swift future combine dispatcher
1个回答
0
投票

我猜想只要锁定它,您就必须在异步块内执行 do 和 catch 操作。 我会尝试这个:

DispatchQueue.global(qos: .background).async {
    do {
        let response = try JSONDecoder().decode( [FeedItemEntity].self, from: data)
    } catch {
        print("JSON Decode error: \(error)")
        promise(.failure(error))
    }
    DispatchQueue.main.async {
        promise(.success(response))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.