Swift 闭包与AnyObject的互转

在习惯了原来的OC开发,可能将多个block做为函数参数,亦或是存入集合类型(NSDictionary、NSArray)的实例中,但在Swift中将闭包存入一个Dictionary或Array中是不行的。其解决方案是用 unsafeBitCast 函数将Swift闭包转为Objective-C的兼容的对象,如下:

//使用`@convention(block)` 关键字,Swift2.0以后@objc_block属性由@convention(block)取代。
typealias CompletionBlock = @convention(block) () -> Void

        let aBlock:CompletionBlock = {
            print("Hello world!")
        }
        let nsArray = NSMutableArray()
        let blockObject = unsafeBitCast(aBlock, AnyObject.self)
        nsArray.addObject(blockObject)
        
        let closureObject = nsArray[0]
        let closure = unsafeBitCast(closureObject, CompletionBlock.self)
        closure()

你可能感兴趣的:(Swift 闭包与AnyObject的互转)