美文网首页
iOS&Swift&OC 闭包和Block的相互转化

iOS&Swift&OC 闭包和Block的相互转化

作者: 闲云悠鹤蝶恋舞 | 来源:发表于2021-05-14 18:28 被阅读0次

    一、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("测试")
    

    相关文章

      网友评论

          本文标题:iOS&Swift&OC 闭包和Block的相互转化

          本文链接:https://www.haomeiwen.com/subject/uttcjltx.html