2 minutes
Integrating Cocoapods with a Swift project
As Apple introduced Swift, their new programming language, you probably wonder how easily you can integrate it with existing Objective-C libraries that are available via CocoaPods.
You begin with creating a Podfile
:
pod 'MKUnits', '~> 2.0.0'
and running pod install
to install pods in your project.
Nice, so far so good. Cocoapods successfully integrated with Xcode 6 project. All we need to do now is to import our pod header file into Swift project. How do you do that?
Definitely not by adding #import <MKUnits/MKUnits.h>
to a Swift file as it would result in this error:
Expected expression
Expected identifier in import declaration
To expose Objective-C files to Swift you must use Objective-C bridging header, as Mix and Match section of Using Swift with Cocoa and Objective-C documentation explains.
To do so, you must create a new Objective-C header file, let’s call it Example-Bridging-Header.h
, and add it to the project. Then, you need to set Objective-C Bridging Header
for your target:
and finally add import statement to the bridge header:
#import <MKUnits/MKUnits.h>
Voilà! Now you can use your pods in Swift.
let kilograms = NSNumber.mass_kilogram(2)()
let pounds = NSNumber.mass_pound(10)()
let result = kilograms.add(pounds)
println(result)
You can also integrate imported Objective-C classes with Swift types. For example, by creating an extension for Int
:
extension Int {
func mass_kilogram() -> MKQuantity {
return MKQuantity.mass_kilogramWithAmount(self)
}
func mass_pound() -> MKQuantity {
return MKQuantity.mass_poundWithAmount(self)
}
}
you can replace previous code with:
let kilograms = 2.mass_kilogram()
let pounds = 10.mass_pound()
let result = kilograms.add(pounds)
println(result)