Swift Language Working with C and Objective-C Using Swift classes from Objective-C code

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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).



Got any Swift Language Question?