我有两个类
,它们都符合相同的协议(protocol)
:
class A {}
class B {}
protocol P {}
extension A: P {}
extension B: P {}
此外,我还有一个回调闭包,其主要参数是传递给某个 C API 函数的 UnsafeMutableRawPointer
:
SomeCFunction(…, …, { (pointerToEitherAOrB: UnsafeMutableRawPointer) in
// Cast pointerToEitherAOrB to either A or B.
})
我不知道指针引用的是两个类
中的哪一个。是否仍然可以将此指针转换为正确的类型?
我的直觉告诉我这是不可能的,我需要使用 super
class
。
最佳答案
使用通用父类(super class)将是更简洁的方法,但首先转换为 AnyObject
似乎也可以:
let aOrB = Unmanaged<AnyObject>.fromOpaque(pointerToEitherAOrB).takeUnretainedValue()
switch aOrB {
case let a as A:
print(a)
case let b as B:
print(b)
default:
print("Something else")
}
关于swift - 将 UnsafeMutableRawPointer 转换为多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768719/