在 Swift 3.0 中,一些 c 语言的 API 调用相比以前发生了较大的变化。包括 GCD 这个经常使用的框架。在Swift <= 2.2 的时代,调用方式和Objective-C中的用法相同,直接调用 @H_502_2@dispatch_async(....) 就可以;这明显不够面向对象。终于,到了 Swift 3.0 ,Apple 把这些 C 语言的 API 改成了更加面向对象的调用方式。现在我们再调用上面那个 API 的话就需要这么写:@H_502_2@DispatchQueue.main.async(execute: () -> Void) 也就是把原来 dispatch** 的派发任务的方法都放到了 DispatchQueue 的类中。同时它还有一个 @H_502_2@DispatchQueue.main 用来获得主队列,也就相当于之前的 @H_502_2@dispatch_get_main_queue,相应的还有 @H_502_2@DispatchQueue.global() 来获得全局队列。下面是 GCD 中c语言类型和 Swift 3.0 中对象的对应关系:
c 语言 API | Swift 3.0 | 示例用法 |
---|---|---|
@H_502_2@dispatch_queue_t | @H_502_2@DispatchQueue | @H_502_2@DispatchQueue(label: queueLabel) |
@H_502_2@dispatch_group_t | @H_502_2@DispatchGroup | @H_502_2@DispatchGroup() |
@H_502_2@dispatch_time_t | @H_502_2@DispatchTime | @H_502_2@DispatchTime.now() + .millisecond(1000) |
@H_502_2@dispatch_block_t | @H_502_2@() -> () | |
@H_502_2@dispatch_queue_attr_t | @H_502_2@DispatchQueueAttributes | @H_502_2@DispatchQueueAttributes.serial |
另外根据 Swift.org 的说法(Migrating to Swift 2.3 or Swift 3 from Swift 2.2) @H_502_2@dispatch_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.
也就是通过一个代码块来初始化变量也可以保证代码只执行一次,同样也是线程安全的,现在可以抛弃 @H_502_2@dispatch_once 了。
上面只列举了一些常用的类型的对应变化,更详细的可以看这里 Modernize libdispatch for Swift 3 naming conventions