简体   繁体   English

Swift async/await - 忽略“考虑使用异步替代函数”警告

[英]Swift async/await - Ignore "Consider using asynchronous alternative function" warning

I have some objective c networking code with completion handler for which swift has automatically generated an async version.我有一些带有完成处理程序的客观 c 网络代码,swift 已为其自动生成异步版本。 I'm calling it at the end of an async function, but in this case I don't need to wait for it.我在async函数结束时调用它,但在这种情况下我不需要等待它。 I'm just passing nil for the completion handler.我只是为完成处理程序传递nil The compiler is giving me a warning:编译器给了我一个警告:

Consider using asynchronous alternative function

Is there a swifty way to avoid this error?有没有一种快速的方法来避免这个错误? Or is the only option wrapping it in another function?或者是将它包装在另一个函数中的唯一选择?

So far the best I've found is to just use a closure:到目前为止,我发现最好的方法是使用闭包:

{
  noNeedToWaitForThis(completion: nil)
}()

This is in Xcode 13.1.这是在 Xcode 13.1 中。

[EDIT] Example objective c method with callback: [编辑] 带有回调的示例目标 c 方法:

typedef void (^LQClientResponseBlock)(BOOL success, id _Nullable object);
- (void)get:(nonnull NSString*)url parameters:(nullable NSDictionary*)parameters completion:(nullable LQClientResponseBlock)completion;

but in this case I don't need to wait for it但在这种情况下,我不需要等待

If you don't say await , then if there were no completion handler alternative, the compiler would error, not warn — because you can't call an async method without saying await .如果你不说await ,那么如果没有完成处理程序替代,编译器会出错,而不是警告——因为你不能不说await就调用async方法。

But there is a completion handler version, so when you don't say await , the compiler takes you to be calling the completion handler version, and warns you, rightly, that the async version exists.但是一个完成处理的版本,所以当你不说await ,编译器会你要调用完成处理的版本,并警告您,正确地,该async版本存在。 And indeed, that is exactly what it seems you want the compiler to think.事实上,这正是您希望编译器思考的内容。

I'm a little unclear what you mean by "I don't need to wait".我有点不清楚你所说的“我不需要等待”是什么意思。 But if you are serious about not wanting to wait, then call the async version from inside a Task initializer:但是,如果您真的不想等待,那么请从 Task 初始值设定项中调用async版本:

Task {
    await callMyAsyncFunction()
}

The code after the right curly brace will execute immediately, without waiting for the Task to end — indeed, without even waiting for it to begin!右花括号后的代码将立即执行,无需等待任务结束——事实上,甚至无需等待任务开始! — and if that means the surrounding method would end, it ends. ——如果这意味着周围的方法将结束,它就会结束。 Basically, Task{} here works, from a structural point of view, just like saying DispatchQueue.someQueue.async .基本上,从结构的角度来看,这里的Task{}可以工作,就像说DispatchQueue.someQueue.async

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM