[swift unboxed]

Safely unboxing the Swift language & standard library

Bridging Swift to Objective-C

On bridging your Swift objects into the world of Objective-C.

24 August 2015 ∙ Objective-C Interop ∙ written by

Based on a talk given at 360iDev 2015. Check out the blog post and video!

You’ve written all kinds of Swift goodness and now want to bring that code over into the Objective-C world. Seeing how well Objective-C makes it into Swift, you’re expecting an equally smooth ride over.

Bay Bridge

Unfortunately, the default is for nothing in Swift to be visible from Objective-C.

Sorry, no entry

There are two annotations you can add to your types in Swift to access them in Objective-C:

  • @objc will make them available in Objective-C

  • dynamic also implies @objc, and also makes the property or method use Objective-C dynamic dispatch

If you want to swizzle or something, you’ll need to use dynamic; just @objc on its own isn’t enough to guarantee things will use objc_msgSend() as it’s still possible that methods will be devirtualized or inlined.

objc and dynamic

Of course this will only work for compatible features. If you have a method in your Swift enumeration, that won’t make it over. If you have an enumeration backed by something other than an Int, it won’t make it over.