Search code examples
objective-cswiftportingdowncast

Downcasting Objective-C object to Swift type fails (silently)


This was discussed here; similar but not identical.

MyView is a Swift subclass of UIImageView. It compiles and its interface appears in the DerivedData/.../*-Swift.h file. But downcasting to it in Obj-C fails. The code:

MyView* myView = (MyView*)viewThatCameFromIB; 
// The Custom Class declared in IB inspector as MyView.

results in this line in the Xcode Variable Viewer:

myView  UIImageView *  0x7fc8e9417e00

This line of code executes with no failure. But sure enough, trying to use the MyView features on the myView variable crashes with unknown selector. Since the cast succeeded in Obj-C, before MyClass was ported, it should also after the port, n'est-ce pas?

I tried:

  • deleting and resetting the Custom Class in IB just in case.
  • breaking this line of code into multiple steps.

Now this worked:

  • instantiate a MyView directly with its init() method

That is, I got a MyView instance:

myView  _TtC12YadaYada11MyView *  0x7f8bc05487d0

(Consequently, I can think of a workaround: write a Swift MyView constructor that takes a UIImageView and uses it to construct itself. But I shouldn't have to. Isn't that what the downcast would do behind the scenes?)


Solution

  • The problem seems to be caused (fixed) by clearing (setting) the Inherit Module From Target boolean for the MyView view, in the Custom Class section of the Identity Inspector. At least in the from-scratch test case. In my particular porting challenge, with 3,000+ files (and 50+ MyViews), there may be confounding factors. But for now, this is the answer.