Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What language level support (if any) does Swift have for asynchronous programming?

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?

like image 560
Ian Ringrose Avatar asked Jun 03 '14 09:06

Ian Ringrose


People also ask

What is asynchronous programming Swift?

An asynchronous function in Swift can give up the thread that it's running on, which lets another asynchronous function run on that thread while the first function is blocked. When an asynchronous function resumes, Swift doesn't make any guarantee about which thread that function will run on.

Which programming language is asynchronous?

JavaScript is an asynchronous and concurrent programming language that offers a lot of flexibility but is also simultaneously single-threaded and non-blocking. Although it's synchronous by nature, JavaScript can benefit from asynchronous code.

Is Swift asynchronous?

Swift now supports asynchronous functions — a pattern commonly known as async/await. Discover how the new syntax can make your code easier to read and understand. Learn what happens when a function suspends, and find out how to adapt existing completion handlers to asynchronous functions.

What is asynchronous programming model?

Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed).


2 Answers

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:

let task = async { () -> () in
  let fetch = async { (t: Task<NSData>) -> NSData in
    let req = NSURLRequest(URL: NSURL.URLWithString("http://www.google.com"))
    let queue = NSOperationQueue.mainQueue()
    var data = NSData!
    NSURLConnection.sendAsynchronousRequest(req,
                                            queue:queue,
      completionHandler:{ (r: NSURLResponse!, d: NSData!, error: NSError!) -> Void in
        data = d
        Async.wake(t)
      })
    Async.suspend()
    return data!
  }

  let data = await(fetch)
  let str = NSString(bytes: data.bytes, length: data.length,
                     encoding: NSUTF8StringEncoding)

  println(str)
}

Also, if you want something like @synchronized, try this:

func synchronized(obj: AnyObject, blk:() -> ()) {
  objc_sync_enter(obj)
  blk()
  objc_sync_exit(obj)
}

var str = "A string we can synchronise on"

synchronized(str) {
  println("The string is locked here")
}
like image 197
al45tair Avatar answered Oct 13 '22 22:10

al45tair


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:

dispatch_async(dispatch_get_main_queue()) {
    println("async hello world")
}
like image 43
Ben Gottlieb Avatar answered Oct 13 '22 21:10

Ben Gottlieb