Stats

Contributors: 1 Thursday, April 14, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Using Swift classes from Objective-C code

Download swift eBook

Example

In the same module

Inside a module named "MyModule", Xcode generates a header named MyModule-Swift.h which exposes public Swift classes to Objective-C. Import this header in order to use the Swift classes:

// MySwiftClass.swift in MyApp
import Foundation

// The class must be `public` to be visible, unless this target also has a bridging header
public class MySwiftClass: NSObject {
    // ...
}
// MyViewController.m in MyApp

#import "MyViewController.h"
#import "MyApp-Swift.h"                    // import the generated interface
#import <MyFramework/MyFramework-Swift.h>  // or use angle brackets for a framework target

@implementation MyViewController
- (void)demo {
    [[MySwiftClass alloc] init];  // use the Swift class
}
@end

Relevant build settings:

  • Objective-C Generated Interface Header Name: controls the name of the generated Obj-C header.
  • Install Objective-C Compatibility Header: whether the -Swift.h header should be a public header (for framework targets).

build setting screenshot


In another module

Using @import MyFramework; imports the whole module, including Obj-C interfaces to Swift classes (if the aforementioned build setting is enabled).