Asynchronous programming is a must for responsive user interfaces when application have to communicate over unpredictable networks (e.g. smart phone applications). The user interface must remain responsive while waiting for results to come back from servers somewhere over the internet.
In most languages, the application programmer has to implement their own state machines (maybe using closures) to respond to asynchronous callbacks and/or coordinate multiply threads using locks.
Both of these are very error prone and not for the fait hearted!
(c# introduced the async keyword to help with this, only time (at least 5 years) will tell if it is a good solution.)
Does Swift have any built in support to assist the writing of asynchronous code?
While it isn't a built-in language feature, it may be interesting to note that it's possible to implement C# style
async
/await
for Swift, and that because of the special syntax afforded to the last closure argument of a function call, it even looks like it might be part of the language.If anyone is interested, you can get code for this on Bitbucket. Here's a quick taster of what's possible:
Also, if you want something like @synchronized, try this:
Swift's approach to asynchronous programming is the same as Objective C's: use Grand Central Dispatch. You can pass closures to gcd dispatch_ functions, just as in ObjC. However, for aesthetic reasons, you can also pass your closure (block) after the close parentheses: