我在Swift 1.2中有一个代码来创建一个dispatch_block_t数组,它工作正常。但是相同的代码在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中,它会抛出以下错误
[dispatch_block_t]无法转换为NSArray
如何使用dispatch_block_t创建NSArray?
更新
我已将上述代码替换为以下代码,
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)
现在,上一个错误消失了。但是我在运行时遇到以下错误,
致命错误:数组元素无法桥接到Objective-C
任何帮助将不胜感激。
答案 0 :(得分:1)
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
*/
答案 1 :(得分:0)
dispatch_block_t
不是从AnyObject继承的,它不是对象。
但您可以修改代码并将AnyObject
更改为Any
,如下所示:
andActionArray : actions as [Any]
它应该适合你。
UPD:
你的函数将参数作为NSArray
,你可以简单地将数组转换为这种类型,这段代码可以在我的快捷游乐场中运行:
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