自从开始,Swift 提供了一些工具来使 ObjC 和 C 更加 Swifty,并且每个版本都添加了更多的功能。现在,在 Swift 3 中,新的
"import as member" 功能允许某些风格的 C API 框架(其中你有一个类似于类的数据类型,以及一堆全局函数来处理它),更像是 Swift 原生的 API。这些数据类型作为 Swift 类导入,它们相关的全局函数作为这些类的方法和属性导入,一些相关的东西,如常量集合,在适当的情况下可以成为子类型。
在 Xcode 8 / Swift 3 beta 中,苹果应用了这个功能(以及其他一些功能)来使 Dispatch 框架更加 Swifty。(还有
Core Graphics。)如果你一直在关注 Swift 开源努力,
this isn't news,但现在它是 Xcode 的一部分是第一次。
Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose "Edit > Convert > To Current Swift Syntax..." in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)
The result is that the common pattern for bouncing work to the background and back now looks like this:
DispatchQueue.global(qos: .userInitiated).async {
let image = self.loadOrGenerateAnImage()
DispatchQueue.main.async {
self.imageView.image = image
}
}
请注意,我们使用的是
.userInitiated
而不是旧的
DISPATCH_QUEUE_PRIORITY
常量之一。 在OS X 10.10 / iOS 8.0中引入了服务质量(QoS)指定符,为系统优先处理工作提供了更清晰的方式,并停用了旧的优先级指定符。 有关详细信息,请参见苹果公司关于后台工作和能源效率的
文档。
顺便说一下,如果您正在保留自己的队列以组织工作,现在获取一个队列的方法看起来像这样(请注意,
DispatchQueueAttributes
是一个
OptionSet
,因此您可以使用集合样式的文字组合选项):
class Foo {
let queue = DispatchQueue(label: "com.example.my-serial-queue",
attributes: [.serial, .qosUtility])
func doStuff() {
queue.async {
print("Hello World")
}
}
}
使用dispatch_after
稍后执行任务?这也是队列的一种方法,它需要一个DispatchTime
,它具有各种数字类型的运算符,因此您可以添加整数或小数秒:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
print("Are we there yet?")
}
你可以在Xcode 8中打开Dispatch API的界面来了解它的使用方法 - 使用Open Quickly查找Dispatch模块,或在你的Swift项目/游乐场中放置一个符号(如
DispatchQueue
),然后按住Command键点击它,从那里浏览模块。(你可以在苹果漂亮的新API参考网站和Xcode文档查看器中找到Swift
Dispatch API,但似乎C版本的文档内容还没有移入其中。)
更多提示请参阅
迁移指南。