How do you use Swift code in an Objective-C project?

← Objective-C answers

Mark the Swift class as @objc (and make it inherit from NSObject), then import the generated header #import "YourTarget-Swift.h" in the .m file that uses it.

import Foundation
 
@objcMembers
public class Greeter: NSObject {
    public func greet(name: String) -> String {
        "Hello, \(name)"
    }
}
// ViewController.m
#import "MyApp-Swift.h"          // target name, spaces and dashes become underscores
 
- (void)viewDidLoad {
    [super viewDidLoad];
    Greeter *greeter = [[Greeter alloc] init];
    NSLog(@"%@", [greeter greetWithName:@"Ada"]);
}
  • Import the Swift header in .m files, not in other headers. In a .h file use a forward declaration: @class Greeter;.
  • In a framework target, use #import <MyFramework/MyFramework-Swift.h> and make sure Defines Module is Yes.
  • Only features that exist in Objective-C are exposed: structs, generics, tuples and enums without raw Int values are not visible.
  • If the header is missing, build the Swift file once so Xcode generates it, and check the product module name in Build Settings.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required