Swift equivalent of Unity3d Coroutines?

好久不见. 提交于 2019-12-12 16:52:28

问题


Looking how to build something similar in Swift 3.

I'm used to using this sort of architecture in Unity3d, perhaps there isn't anything similar to handle async data. I've heard of completion blocks + using protocols/delegates to pass data in Swift but I thought it'd be easier to have a public function that gets the data and then use a coroutine to wait until all the data is in the VC to start things up.

Here is C# code I'd use to create them:

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);
}

回答1:


No, Swift do not currently support Unity/C# style coroutines (i.e., yield return style constructs). Such feature is pretty cool by the way ;-)

Having said that, you might want to take a look in the Async framework for a somewhat valid alternative (if you are really looking for async/await abstractions):

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

As for Swift native support, we might need to wait for Swift ≥ 5 for something like that to come along:

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.



来源:https://stackoverflow.com/questions/43505101/swift-equivalent-of-unity3d-coroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!