Swift 3.0 中 GCD 相关函数的语法

在 Swift 3.0 中,一些 c 语言的 API 调用相比以前发生了较大的变化。包括 GCD 这个经常使用的框架。在Swift <= 2.2 的时代,调用方式和Objective-C中的用法相同,直接调用 dispatch_async(....) 就可以;这明显不够面向对象。终于,到了 Swift 3.0 ,Apple 把这些 C 语言的 API 改成了更加面向对象的调用方式。现在我们再调用上面那个 API 的话就需要这么写:DispatchQueue.main.async(execute: () -> Void) 也就是把原来 dispatch** 的派发任务的方法都放到了 DispatchQueue 的类中。同时它还有一个 DispatchQueue.main 用来获得主队列,也就相当于之前的 dispatch_get_main_queue,相应的还有 DispatchQueue.global() 来获得全局队列。下面是 GCD 中c语言类型和 Swift 3.0 中对象的对应关系:

c 语言 API Swift 3.0 示例用法
dispatch_queue_t DispatchQueue DispatchQueue(label: queueLabel)
dispatch_group_t DispatchGroup DispatchGroup()
dispatch_time_t DispatchTime DispatchTime.now() + .millisecond(1000)
dispatch_block_t () -> ()
dispatch_queue_attr_t DispatchQueueAttributes DispatchQueueAttributes.serial

另外根据 Swift.org 的说法(Migrating to Swift 2.3 or Swift 3 from Swift 2.2dispatch_once 在Swift 3.0 中不再提供了:
==The free function dispatch_once is no longer available in Swift. In Swift,you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided. Example:==

let myGlobal = { … global contains initialization in a call to a closure … }() _ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.

也就是通过一个代码块来初始化变量也可以保证代码只执行一次,同样也是线程安全的,现在可以抛弃 dispatch_once 了。

上面只列举了一些常用的类型的对应变化,更详细的可以看这里 Modernize libdispatch for Swift 3 naming conventions

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...