1
votes

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)

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

[dispatch_block_t] is not convertible to NSArray

How can I create an NSArray with dispatch_block_t?

UPDATE:

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,

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

Any help will be appreciated.

2

2 Answers

1
votes
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
*/
0
votes

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