Wikkle_A Wikkle_A -4 years ago 123
Swift Question

Swift equivalent of Unity3d Coroutines?

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()

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

yield break;

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

void Start()

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download