swift - 将 UnsafeMutableRawPointer 转换为多种类型

标签 swift

我有两个,它们都符合相同的协议(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/

相关文章:

ios - 加载新消息 Swift 4.2 和 Firebase

swift - @EnvironmentObject 符合协议(protocol): Xcode not compiling

ios - 获取保存到照片库的图像的 PHAsset/localIdentifier

ios - 单击按钮时无法播放一系列图像

Swift - 读取文本 : line1 = variable, line2 = 变量等

ios - 以编程方式为每个 ios 屏幕设计在底部动态创建 CGPoint

swift - 在主 bundle 的子目录中查找文件时获取nil

xcode - 使用scheduledTimerWithTimeInterval的NSDate错误: Extra argument 'selector' in call

ios - 视频在 xcode 模拟器上播放但不在设备上播放

key - 如何在 Swift 中将键分配给 SKActions