如何在Swift 2.0中创建dispatch_block_t数组? [英] How to create an array of dispatch_block_t in Swift 2.0?

查看:134
本文介绍了如何在Swift 2.0中创建dispatch_block_t数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift 1.2中有一个代码来创建一个dispatch_block_t数组,它工作正常。但是相同的代码在Swift 2.0中引发了错误。

I have a code in Swift 1.2 to create an array of dispatch_block_t and it works fine. But the same code throws error in Swift 2.0.

var menuView: btSimplePopUP!

let actions: [dispatch_block_t] = [{self.pickImages()},
    {self.takePicture()},
    {self.pickVideos()},
    {self.shootVideo()},
    {self.recordAudio()},
    {self.closeView()}]

menuView = btSimplePopUP(itemImage: imgs as [AnyObject],
    andTitles: titles as [AnyObject],
    andActionArray:  actions as NSArray as [AnyObject],
    addToViewController: self)

上面的代码在Swift 1.2中运行正常。但是在Swift 2.0中,它会抛出以下错误

The above code works fine in Swift 1.2. But in Swift 2.0, it throws the following error


[dispatch_block_t]无法转换为NSArray

[dispatch_block_t] is not convertible to NSArray

如何使用dispatch_block_t创建NSArray?

How can I create an NSArray with dispatch_block_t?

更新:

我已将以上代码替换为以下代码,

I have replaced the above code with the following one,

let actions: [Any] = [{self.pickImages()},
                    {self.takePicture()},
                    {self.pickVideos()},
                    {self.shootVideo()},
                    {self.recordAudio()},
                    {self.closeView()}]

menuView = btSimplePopUP(itemImage: imgs as [AnyObject],
        andTitles: titles as [AnyObject],
        andActionArray:  actions as! [AnyObject],
        addToViewController: self)

现在,上一个错误消失了。但是我在运行时遇到以下错误,

Now, the previous error is gone. But I am getting the following error in run time,


致命错误:数组元素无法桥接到Objective-C

fatal error: array element cannot be bridged to Objective-C

任何帮助将不胜感激。

推荐答案

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
*/

这篇关于如何在Swift 2.0中创建dispatch_block_t数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆