I'm trying to build an Objective-C block in Swift 2 in order to add it to an NSArray
like so :
typealias CompletionBlock = () -> Void
let aBlock:CompletionBlock = {
print("Hello world!")
}
let nsArray = NSMutableArray()
nsArray.addObject(aBlock) // Error
I know it will work just fine with a Swift array, but I need an NSArray
here for compatibility with existing Objective-C code. And if I use a swift array the compiler will refuse to cast it to an NSArray
because it won't be a [AnyObject]
(it will be a [Any]
).
The problem here is that a swift closure is not an object contrary to Objective-C blocks which are objects behind the scene (they are instances of NSBlock
which is a subclass of NSObject
)
So my question is : How do a create an Objective-C block in swift ? I've tried using @convention (block)
in the typealias but it doesn't work.