天天看点

[swift] Async

async

[swift] Async

https://github.com/duemunk/async

syntactic sugar in swift for asynchronous dispatches in grand central dispatch (gcd)

这是一个swift中gcd的语法糖库。

async sugar looks like this:

async使用起来就像这样子:

instead of the familiar syntax for gcd:

替换了下面的这种显示方式:

install

benefits

less verbose code 更少的冗余代码

less code indentation 更少的缩进风

things you can do

supports the modern queue classes:

支持常用的queue类:

chain as many blocks as you want:

你可以将不同的block链接起来使用:

store reference for later chaining:

也可以分开使用:

custom queues:

自定义queue:

dispatch block after delay:

延时执行:

cancel blocks that aren't already dispatched:

取消没有启动的线程:

wait for block to finish – an ease way to continue on current queue after background task:

等待一个block运行结束:

how does it work

the way it work is by using the new notification api for gcd introduced in os x 10.10 and ios 8. each chaining block is called when the previous queue has finished.

本库使用了 ios 8 提供的通知 api 来完成相关功能,每一个block都会在上一个block执行完了之后继续执行:

the syntax part of the chaining works by having class methods on the <code>async</code> object e.g. <code>async.main {}</code> which returns a struct. the struct has matching methods e.g. <code>thestruct.main {}</code>.

known bugs

modern gcd queues don't work as expected in the ios simulator. see issues 13, 22.

known improvements

the <code>dispatch_block_t</code> can't be extended. workaround used: wrap <code>dispatch_block_t</code> in a struct that takes the block as a property.

bonus stuff

there is also a wrapper for <code>dispatch_apply()</code> for quick parallelisation of a <code>for</code> loop.

note that this function returns after the block has been run all 100 times i.e. it is not asynchronous. for asynchronous behaviour, wrap it in a an <code>async</code> block like <code>async.main{ apply.background(100) { ... } }</code>.