我有 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/