swift - 如何在 Swift 3 中将 __NSMallocBlock__ 转换为其基础类型?

标签 swift casting swift3 unsafe-pointers

我有 a trick帮助测试在 Swift 2.x 中工作的 UIAlertController:

extension UIAlertController {

    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void

    func tapButtonAtIndex(index: Int) {
        let block = actions[index].valueForKey("handler")
        let handler = unsafeBitCast(block, AlertHandler.self)

        handler(actions[index])
    }

}

这在 Swift 3.x 下失败并出现 fatal error: can't unsafeBitCast between types of different sizes,这让我相信可能有一种方法可以使转换工作。任何人都可以解决吗?

最佳答案

找到了一个适用于 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<AnyObject>.passUnretained(block as AnyObject).toOpaque())
            let handler = unsafeBitCast(blockPtr, to: AlertHandler.self)
            handler(actions[index])
        }
    }

}

(最初,block 值是实际的 block ,而不是指向 block 的指针——您显然不能将其转换为指向 AlertHandler 的指针)

关于swift - 如何在 Swift 3 中将 __NSMallocBlock__ 转换为其基础类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628852/

相关文章:

Java 对象列出优点和缺点

rust - FFI:将可空指针转换为选项

ios - 用逗号分隔的单独的 json 内容

ios - 验证文本字段Swift 3

ios - UINavigationController 作为 MSMessagesAppViewController 的 subview

ios - 为一年中的每一天生成 View Controller

将 volatile 表达式的结果转换为 void

ios - 对使用 UserDefaults 确保删除的项目在 TableView 中保持删除感到困惑

ios - 从不是 viewController 的 swift 文件更新时进度条崩溃

ios - 查询 Firebase 用户以检查联系人是否存在于数据库中