Monday, 28 July 2014

Having Swift and Objective C in a same project

Mix and Match Overview:

Objective C and Swift files can coexist in a single project, whether the project was originally an Objective -C or Swift project. This natural workflow makes creating mixed-language app and framework targets as straight forward as creating an app or framework target written in a single language.

The process for working with mixed-language targets differs slightly depending on whether you're writing an app or a framework. The general import model for working with both languages within the same target is depicted below and described in more detail in the following sections.

              image: ../Art/DAG_2x.png

Importing Objective-C into Swift:
To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.
                         image: ../Art/bridgingheader_2x.png

If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding "-Bridging-Header.h". For information on the product module name, see Naming Your Product Module.

You'll need to edit this file to expose your Objective-C code to your Swift code.

To import Objective-C code into Swift from the same target
1. In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift. For example:


    i.   #import "XYZCustomCell.h"
    ii.  #import "XYZCustomView.h"
    iii. #import "XYZCustomViewController.h"

2. Under Build Settings, make sure the Objective-C Bridging Header build setting under Swift Compiler - Code Generation has a path to the header.

The Path should be relative to your project, similar to the way your info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

Any public Objective-C headers listed in this bridging header file will be visible to Swift. The Objective-C functionality will be available in any Swift file within that target automatically, without any import statements. Use your custom Objective-C code with the same Swift syntax you use with system classes.

  1.   let myCell = XYZCustomCell( )
  2.   myCell.subTitle = "A custom cell"


No comments:

Post a Comment