7

I'm dealing with a scenario where there is an Objective-C class that I am weakly linking:

__attribute__((weak_import))
@interface MyClass : NSObject @end

I'm also using this class in my Swift code:

let myObject : MyClass = MyClass()

However, this always crashes when run in swift_getObjCClassMetadata, even if I'm only casting an object that's already of type MyClass

let myObject : MyClass = otherObj as? MyClass

Is there any way to successfully cast to, or utilize these classes from Swift?

mattsven
  • 22,305
  • 11
  • 68
  • 104
  • Are you weak linking an entire framework or a single class? – JAL Mar 09 '16 at 15:04
  • A single class, in this. – mattsven Mar 09 '16 at 15:07
  • Hmm, can't seem to reproduce this scenario, presumably since the library I created up for weak linking isn't set up the same way as yours. Would you mind setting up a small project that reproduces the issue? – JAL Mar 09 '16 at 15:17
  • I'm going to sound a little crazy here, but I can't replicate it now in a new project, either. Experimenting...! – mattsven Mar 09 '16 at 17:42
  • No worries, keep us updated. – JAL Mar 09 '16 at 20:02
  • After extended testing, I've come to the conclusion that this has a lot to do with how the main app is compiled. In my tests, creating an app from scratch loads the classes and can use them without issue. – mattsven Mar 10 '16 at 02:15
  • I'd like to know this too: all answers on the web point to #availability() which is not useful here: it is only for OS features, not third-party frameworks. – Daniel Nov 14 '17 at 03:15
  • @Daniel You can always detect the presence of an Objective-C class using `NSClassFromString("...") != nil` – mattsven Nov 15 '17 at 14:37

0 Answers0