Dennis Vennink
Dennis Vennink

Reputation: 1173

Casting an UnsafeMutableRawPointer to Multiple Types

I've got two classes that both conform to the same protocol:

class A {}
class B {}

protocol P {}

extension A: P {}
extension B: P {}

In addition, I've got a callback closure whose main argument is a UnsafeMutableRawPointer passed in to some C API function:

SomeCFunction(…, …, { (pointerToEitherAOrB: UnsafeMutableRawPointer) in
  // Cast pointerToEitherAOrB to either A or B.
})

I don't know which of the two classes the pointer refers to. Would it still be possible to cast this pointer to the correct type?

My intuition tells me this wouldn't be possible and that I will need to use a super class.

Upvotes: 2

Views: 118

Answers (1)

Martin R
Martin R

Reputation: 539685

Using a common superclass would be the cleaner approach, but converting to AnyObject first seems to work as well:

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")
}

Upvotes: 4

Related Questions