一、Swift的闭包 -> OC的block
// 将closure类型转化为block类型(Swift的闭包 -> OC的block)
let closure = {
(str: String)->Void in
}
let block = closure as @convention(block) (String) -> Void
let blockObject = unsafeBitCast(block, to: AnyObject.self)
// 转化完毕blockObject就是一个block了,就可以在OC中正常使用了,也可以放入params中传递了
let params = ["callback":blockObject] as [AnyHashable:Any]
二、OC的block -> Swift的闭包
// 将block转化为closure类型(OC的block -> Swift的闭包)
// callblock是OC的带一个字符串参数的block
// let testBlock = actionParams["callblock"]
typealias ClosureType = @convention(block) (String) -> Void
let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(testBlock as AnyObject).toOpaque())
let closure = unsafeBitCast(blockPtr, to: ClosureType.self)
// closure就是转化过后的闭包
closure("测试")
网友评论