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

前端 未结 2 475
臣服心动
臣服心动 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: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 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")
    }
    

提交回复
热议问题