簡體   English   中英

如何在swift變量中存儲這個objectiveC塊?

[英]How to store this objectiveC block inside a swift variable?

這是objectiveC塊

@property (copy) void (^anObjcBlock)();

anObjcBlock = ^{
    NSLog(@"Yea man this thing works!!");
};
NSMutableArray *theArrayThatHasTheBlockInItAtIndexZero = [NSmutableArray array];
[theArrayThatHasTheBlockInItAtIndexZero addObject:anObjBlock];

這是我在swift中所做的:

var theBlock: ( ()->Void) ?

theBlock = theArrayThatHasTheBlockInItAtIndexZero[0] as? ()->Void
//Now call the block
theBlock!()

但有了這個我得到運行時錯誤。 基本上, theBlock = theArrayThatHasTheBlockInItAtIndexZero[0] as? ()->Void theBlock = theArrayThatHasTheBlockInItAtIndexZero[0] as? ()->Void語句會使theBlock nil因為as? 失敗。 當我把聲明改為theBlock = theArrayThatHasTheBlockInItAtIndexZero[0] as! ()->Void theBlock = theArrayThatHasTheBlockInItAtIndexZero[0] as! ()->Void ,我得到一個運行時錯誤 在此輸入圖像描述

我不知道還能做什么。 這是一個空項目,其中確實沒有代碼。

在這種情況下,看起來問題來自NSMutableArray

[NSMutableArray objectAtIndex:]在Objective-C中返回id ,由Swift轉換為AnyObject

如果您嘗試將AnyObject強制轉換() - > Void,則會出現錯誤。

解決方法如下:

//Create your own typealias (we need this for unsafeBitcast)
typealias MyType = @convention(block) () -> Void

//Get the Obj-C block as AnyObject
let objcBlock : AnyObject = array.firstObject! // or [0]

// Bitcast the AnyObject Objective-C block to a "Swifty" Objective-C block (@convention(block)) 
//and then assign the result to a variable of () -> Void type

let block : () -> Void = unsafeBitCast(objcBlock, MyType.self)

//Call the block

block()

這段代碼適合我。


有趣的事實

如果您編輯Objective-C代碼看起來像這樣......

//Typedef your block type
typedef void (^MyType)();

//Declare your property as NSArray of type MyType
@property (strong) NSArray<MyType>* array;

Swift現在將數組類型報告為[MyType]!

出於某種原因, NSMutableArray上的泛型似乎沒有被Swift選中。

盡管如此,如果執行以下操作,您將收到運行時錯誤:

 let block : MyType? = array[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM