2015-11-12 54 views
1

我有一個Swift 1.2中的代碼來創建一個dispatch_block_t數組,它工作正常。但是相同的代碼在Swift 2.0中拋出錯誤。如何在Swift 2.0中創建dispatch_block_t數組?

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] is not convertible to NSArray

如何使用dispatch_block_t創建NSArray?

UPDATE:

我已經取代了上面的代碼與下面的一個,

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) 

現在,以前的錯誤已經一去不復返了。但我在運行時出現以下錯誤,

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

任何幫助將不勝感激。

回答

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

感謝您的回覆。我需要將這個數組作爲NSArray傳遞給一個函數。傳遞時,我得到這個錯誤,「[dispatch_block_t]不能轉換爲NSarray」。任何想法將其作爲NSArray傳遞? –

+0

NSArray不能保存值類型。爲此,您需要將dispatch_block_t框。請參閱我的更新回答 – user3441734

+0

謝謝@ user3441734現在,我可以將其轉換爲NSArray。但是我在函數定義'*** NSForwarding:warning:'類'ProjName的對象0x7a5841b0'中收到以下錯誤。Block''沒有實現methodSignatureForSelector: - 提前出現故障 無法識別的選擇器 - [ProjName.Block copy]' –

0

dispatch_block_t不是從AnyObject繼承的,它不是對象。 但是你可以修改代碼,改變AnyObjectAny這樣的:

andActionArray : actions as [Any] 

它應該爲你工作。

UPD:

你的函數將作爲PARAM 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 
+0

感謝您迴應..但現在我收到以下錯誤「[dispatch_block_t]不能轉換爲[Any]」 –

+0

顯示您的'btSimplePopUP' init函數?那裏的'andActionArray'是什麼類型?如果沒有你的代碼,我不能幫你更多 – katleta3000

+0

btSimplePopUp是一個開源的,我用來顯示一個菜單。初始化函數的鏈接是https://github.com/balram3429/btSimplePopUp/blob/master/btSimplePopUp/btSimplePopUP.m並且初始化函數從行開始:284 –