How to create an array of dispatch_block_t in Swift 2.0?

血红的双手。 提交于 2019-12-01 01:36:14
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = false

import Foundation

let a: dispatch_block_t = {
    print("a")
}
let b: dispatch_block_t = {
    print("b")
}
let arr = [a,b]
print(arr.dynamicType)
arr.forEach { (b) -> () in
    b()
}
/* prints
Array<@convention(block) () -> ()>
a
b
*/
class Block {
    var block: dispatch_block_t
    init(block: dispatch_block_t){
        self.block = block
    }
}
let block1 = Block(block: a)
let block2 = Block(block: b)

let arr2: NSArray = [block1,block2]
print(arr2)
arr2.forEach { (p) -> () in
    (p as? Block)?.block()
}
/* prints
(
    Block,
    Block
)
a
b
*/

dispatch_block_t is not inherited from AnyObject, it's not object. But you can modify your code and change AnyObject to Any like this:

andActionArray : actions as [Any]

And it should work for you.

UPD:

Your function takes param as NSArray, you can simply cast your array to this type, this code works in my swift playground:

func pickImages() {}
func takePicture() {}
func shootVideo() {}

let actions: [dispatch_block_t] = [{pickImages()},
    {takePicture()},
    {shootVideo()}]
var actionArray: NSArray = actions as NSArray // pass it to the btSimplePopUP init
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!