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

前端 未结 2 468
臣服心动
臣服心动 2021-02-05 09:21

Asynchronous programming is a must for responsive user interfaces when application have to communicate over unpredictable networks (e.g. smart phone applications). The user i

相关标签:
2条回答
  • 2021-02-05 09:51

    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")
    }
    
    0 讨论(0)
  • 2021-02-05 09:57

    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")
    }
    
    0 讨论(0)
提交回复
热议问题