A super simple example of adding Objective-C files to a Swift project in Xcode

Getting Started

  1. Inside a Swift project select File -> New -> File .. [or cmd + N]
  2. Select iOS -> Cocoa Touch Class
  3. Provide class name (e.g. HelloSwift), set to Subclass of NSObject and set language to Objective-C
  4. Click Next
  5. Agree to Bridging Header
  6. Navigate to Bridging Header: YourProjectName-Bridging-Header.h
  7. Insert the following text into Bridging Header: #import "HelloSwift.h"

Adding the code

Place the following text in your HelloSwift.h file:

#import <Foundation/Foundation.h>
@interface HelloSwift : NSObject
-(NSString *)helloObjectiveC:(NSString *)name;
@end

Place this code in your HelloSwift.m file:

#import "HelloSwift.h"
@implementation HelloSwift
-(NSString *)helloObjectiveC:(NSString *)name {
    NSString *myString = [NSString stringWithFormat:@"Hello %@, my name is Objective-C", name];
    return myString;
}
@end

Inside the viewDidLoad of your initial view controller class file add the following lines of Swift:

var myHello = HelloSwift()
println(myHello.helloObjectiveC("Swift"))

Build and run.


Endorse on Coderwall

Comments