Cast closures/blocks

前端 未结 4 1828
粉色の甜心
粉色の甜心 2020-12-05 15:35

In Objective-C, I often pass around blocks. I use them very often to implement patterns that help avoid storing stuff into instance variables, thus avoiding threading/timing

4条回答
  •  囚心锁ツ
    2020-12-05 15:52

    I like GoZoner's solution - wrap the block in a custom class - but since you asked for the actual "Swift way" to perform the cast between a block and an AnyObject, I'll just give the answer to that question: cast with unsafeBitCast. (I'm guessing that this is more or less the same as Bryan Chen's reinterpretCast, which no longer exists.)

    So, in my own code:

    typealias MyDownloaderCompletionHandler = @objc_block (NSURL!) -> ()
    

    Note: in Swift 2, this would be:

    typealias MyDownloaderCompletionHandler = @convention(block) (NSURL!) -> ()
    

    Here's the cast in one direction:

    // ... cast from block to AnyObject
    let ch : MyDownloaderCompletionHandler = // a completion handler closure
    let ch2 : AnyObject = unsafeBitCast(ch, AnyObject.self)
    

    Here's the cast back in the other direction:

    // ... cast from AnyObject to block
    let ch = // the AnyObject
    let ch2 = unsafeBitCast(ch, MyDownloaderCompletionHandler.self)
    // and now we can call it
    ch2(url)
    

提交回复
热议问题