Swift & Cocoapods

How to integrate Cocoapods into a vanilla Swift project

So, everyone’s excited about the Objective-C successor Apple unveiled yesterday. After the rush to download Xcode 6 you created your first swift project and start hacking away, but your code feels alone. It wants to play with all the great libraries out there, so quick! Let’s add some pods!

First you create a Podfile:

platform :ios, '7.0'
pod 'AFNetworking', '~> 2.2.4'

and run pod install to find your pods nicely integrated with your project.

But how to talk to your Objective-C pods from your Swift files? What to import and where?

Apple shows how to mix ‘n match Objective-C and Swift mentions the bridging header. That’s exactly what you’re missing. So hurry, let’s create one!

Create a new header file and reference it from your build settings

This file’s where the magic happens. Import everything you want to access from your Swift code inside the bridging header:

#import <AFNetworking/AFNetworking.h>

From now on you can use your favorite libraries from your new favorite programming language:

let manager = AFHTTPRequestOperationManager()
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)

Big success!

Not so fast though. If you’re like me and you longed to see how the ReactiveCocoa syntax fits into Swift you’re going to run into trouble. Appearently there’s a bug that causes the compilation to fail on RACSignals not, and and or methods. Let’s hope this will be fixed soon.

Until then, happy Swifting! And go watch some courses on functional programming while you’re at.