Swift is out there for about a year and it’s a great programming language. I think that almost every iOS/OSX developer out there has already written couple of things in Swift (if you haven’t, go ahead and try, you won’t regret it, I promise). Although, we have many years of libs and frameworks built using Objective-C and sooner or later a project may have both Swift and Objective-C working together.
Fortunately, Apple gave us a book and a couple of WWDC session (here and here) with the intent to help developers on this task.
For those who have some experience with this integration knows that casting plays an important role. So, todays hint will dig into an poor documented protocol called
The documentation, which is only founded in header files says:
A Swift Array or Dictionary of types conforming to ObjectiveCBridgeable can be passed to Objective-C as an NSArray or NSDictionary, respectively. The elements of the resulting NSArray or NSDictionary will be the result of calling bridgeToObjectiveC on each element of the source container.
Ok, but there is something else you can do with that, which is very handy.
Suppose that you have this class in Objective-C:
1 2 3 4 5 6 7 8
Now you want to easily cast this class into a Swift struct. Yes, we can! All you have to do is conform to
_ObjectiveCBridgeable, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
1 2 3 4 5 6 7 8 9 10 11 12
Oh, that’s so beautiful, don’t you think? :]