Objective-C inside the Swift?

Asked

Viewed 118 times

0

Is there any way to place Objective-C classes within Swift projects?

  • 1

    this refers to creating an Obj-C class and using it in the project or placing lines of Obj-C code inside the same Swift file?

  • Refers to using lines of code within Swift.

1 answer

1

First create a new "Cocoa Touch Class" in File > New > File

Put Objective-C as language: Criação da classe

After clicking to proceed the Xcode will ask if Voce wants to create a Bridging Header (it is the class that will make a "bridge" between the two languages by importing the Objective-C code into Swift).

Click to create: inserir a descrição da imagem aqui

in this class import the . h of the class you want to use in the Swift project, in this case I imported the class "Import"

  #import "Import.h" 

in the Import class only one method was created to print a string

//Código do Import.h


#import 

@interface Import : NSObject

-(void) printName:(NSString*)name;

@end
//Código do Import.m

#import "Import.h"

@implementation Import
-(void) printName:(NSString*)name{
    NSLog(@"%@", name);
}
@end
 

and now just instantiate the class of any part of the Swift code and call your method, for example in viewDidLoad from Viewcontroller:

override func viewDidLoad() {
   super.viewDidLoad()

   var i = Import()
   i.printName("Maria")
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.