Dispatch3 是 iOS9 Dispatch 框架的包装器,提供与 iOS10 中的新 Dispatch 框架相同的语法和功能。
我正在观看 Swift 3 中的 GCD WWDC 会议,并想要开始使用新的、更干净的语法,而无需等待 Xcode 8 发布。所以我决定看看我是否能在 Xcode 7.3 中复制其功能子集。
到目前为止,它只包含了基本功能 - 但您仍然可以使用这些功能做很多事情!以下是您可以做的
import Dispatch3
class DispatchStuff
{
let sq = DispatchQueue("com.example.some_queue", attr: .serial)
let cq = DispatchQueue("com.example.another_queue", attr: .concurrent)
let x = 5
func foo() throws
{
// You can return from a sync closure! And you don't have to
// reference self (closure is @noescape)
let y = sq.sync { return x }
// You can also throw from a sync closure!
try sq.sync { throw SomeException }
// dispatch_after is much simpler
sq.after(.now() + 5) { print "Isn't that much easier?" }
sq.after(.now() + .milliseconds(500)) { print "No conversions necessary" }
// Dispatch groups!
let g = DispatchGroup()
cq.async(group: g) { /* Do the thing */ }
cq.async(group: g) { /* Do the other thing */ }
g.enter()
someObject.customThing(completion: { g.leave() })
group.notify { /* Do when thing, other thing, and custom thing are done */ }
// Barrier blocks!
for i in 0..<10
{
cq.async { /* Do the thing */ }
}
cq.async(flags: .barrier) { /* called after cq is drained */ }
// Dispatch on the main queue
DispatchQueue.main.async { /* update the UI */ }
// Dispatch on a global queue
DispatchQueue.global(attributes: .qosBackground).async { ... }
}
func bar()
{
// Preconditions!
dispatchPrecondition(.onQueue(sq))
dispatchPrecondition(.notOnQueue(cq))
print("I feel safer already")
}
}
该项目永远无法达到 100% 兼容性,甚至可能无法接近。毕竟,它有一个有限的寿命 - Xcode 8 发布后就会变得过时。话虽如此,我会根据自己的需要添加更多功能。欢迎大家贡献。
要运行示例项目,请克隆仓库,然后从 Example 目录中首先运行 pod install
。
Dispatch3 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "Dispatch3"
David Whetstone, [email protected]
Dispatch3 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。