How do I cast an __NSMallocBlock__ to its underlying type in Swift 3?

后端 未结 3 1516
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 11:25

I had a trick to help test UIAlertController that worked in Swift 2.x:

extension UIAlertController {

    typealias AlertHandler = @convention(b         


        
3条回答
  •  再見小時候
    2021-01-05 11:44

    Found a solution that works in Swift 3.0.1

    extension UIAlertController {
    
        typealias AlertHandler = @convention(block) (UIAlertAction) -> Void
    
        func tapButton(atIndex index: Int) {
            if let block = actions[index].value(forKey: "handler") {
                let blockPtr = UnsafeRawPointer(Unmanaged.passUnretained(block as AnyObject).toOpaque())
                let handler = unsafeBitCast(blockPtr, to: AlertHandler.self)
                handler(actions[index])
            }
        }
    
    }
    

    (Originally, the block value was the actual block, not a pointer to the block—which you obviously can't cast to a pointer to AlertHandler)

提交回复
热议问题