Bridging between Objective-C and Swift - dummies

Bridging between Objective-C and Swift

By Jesse Feiler

There are cases where you need to mix and match code between the Objective-C and Swift languages. When it comes to the frameworks, the engineers at Apple are working through the interfaces to provide Swift interfaces alongside the Objective-C versions so that you can use either one to get to the framework in your own app.

Sometimes you need to use a bridge to get to code that you need. A typical example occurs when you use Core Data with relationships. Given a data model for Core Data (often provided as part of a template), you can use Editor→Create NSManagedObject Subclass to create files to add to your project. Choose the option to create Objective-C files. At the bottom of the .h file that’s created, you’ll find declarations of methods for members of relationships such as these:

@interface WhereCategory (CoreDataGeneratedAccessors)
- (void)addNecklaceObject:(Necklace *)value;
- (void)removeNecklaceObject:( Necklace *)value;
- (void)addNecklaces:(NSSet *)values;
- (void)removNecklaceses:(NSSet *)values;

This code lets you add or remove individual related objects or the whole set of related objects. When you try to create the files, you’ll see an alert asking you if you’d like to create a bridging header.

The file that is created will be named MyProject-Bridging-Header.h. Simply add import statements to that file for the Objective-C .h files, as shown here, and you’ll be ready to build your mix-and-match project.

//  Use this file to import your target’s public headers
//  that you would like to expose to Swift.
#import “Bracelet.h”
#import “Pendant.h”
class DetailViewController: UIViewController {
  //@IBOutlet weak var detailDescriptionLabel: UILabel!
  @IBOutlet var mapView: MKMapView!
  @IBAction func actionButton(sender: AnyObject) {
    var detailItem: Event? = nil { //AnyObject? {
      didSet {
        // Update the view.
    func configureView() {
      // Update the user interface for the detail item.
      var pin = MKPointAnnotation ()
      var long:Double = detailItem!.longitude as Double
      var lat:Double = detailItem!.latitude as Double
      var myCoordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat as CLLocationDegrees, longitude: long as CLLocationDegrees)
      pin.coordinate = myCoordinate
      pin.title = “Test Title”;
      pin.subtitle = “Test Subtitle”;
      if var myMapView = self.mapView {
    override func viewDidLoad() {
      // Do any additional setup after loading the view, typically from a nib.
    override func didReceiveMemoryWarning() {
      // Dispose of any resources that can be recreated.