Swift 等同于 Unity3d 协程?

标签 swift unity3d swift3 async-await coroutine

研究如何在 Swift 3 中构建类似的东西。

我习惯在 Unity3d 中使用这种架构,也许没有类似的东西来处理异步数据。我听说过完成 block +使用协议(protocol)/委托(delegate)在 Swift 中传递数据,但我认为拥有一个获取数据的公共(public)函数然后使用协程等待所有数据都在 VC 中会更容易开始吧。

这是我用来创建它们的 C# 代码:

List<Int> data = new List<Int>;

private IENumerator get_data() 
{ 
    run_async_func_to_get_data();

    while(data.count == 0) 
    {
       yield return null;
    }

    yield break;
}


private IENumerator start_game()
{
   yield return get_data();
   yield return use_data();
}

void Start() 
{
    StartCoroutine(start_game);
}

最佳答案

不,Swift 目前不支持 Unity/C# style coroutines (即,yield return 样式构造)。顺便说一下,这样的功能非常酷 ;-)

话虽如此,您可能想看看 Async framework对于一个有点有效的替代方案(如果你真的在寻找异步/等待抽象):

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

至于 Swift 原生支持,我们可能需要 wait for Swift ≥ 5对于类似的事情:

Actors, async/await, atomicity, memory model, and related topics. This area is highly desired by everyone, as it will open the door for all sorts of new things on the client, server and more. We plan to start formal discussions about this in Phase 2, but it is unfortunately crystal clear that a new concurrency model won’t be done in time for the Swift 4 release. This is simply because it will take more than a 12 months to design and build, and we want to make sure to take time to do it right. It also makes sense for the memory ownership model to be better understood before taking this on.

关于Swift 等同于 Unity3d 协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505101/

相关文章:

C# 泛型函数

ios - Swift3 中的 "Cannot convert value of type"错误

ios - 在 Swift 3.0 中录制视频时 Flash 不起作用

firebase - EXC_BAD_ACCESS code=2 在 Podfile 中包含 Firebase/Auth

快速将 Any 转换为闭包

ios - 编辑表格时的附加选项卡

ios - 使用Unity3d中的更改更新xcode项目

objective-c - 如何调用接受 block 字典作为 Swift 参数的 Objective-C 函数?

ios - 在 swift 中的自定义 View 上播放透明视频(H.264,AAC)

c# - 如果语句体不执行