How to integrate Objective-C and Swift?

3

I'm doing a project in Swift and would like to use some files in Objective-C. Is it possible to do this?

In case I installed using Cocoa Pods , I do not know if that influences anything.

    
asked by anonymous 16.01.2015 / 19:09

1 answer

6

Using classes in Objective-C in Swift

Creating a Bridging Header

When you drag the files to the project

Dragging a .m Xcode will will most likely show you this window:

JustanswerYesandXcodedoesallthemagicforyou!

WhenyouuseCocoaPods

(orwhenXcodedoesnotmagicit)

  • CreateanHeaderofObjective-CandObjective-CHeader.
  • Gototheprojectsettings>BuildSettings>SwiftCompiler-CodeGenerationandenterthenameofyourHeader.

Youcandoasinthisimage: But be sure to change the start of to to ensure that the code will compile on other machines.

Importing classes Objective-C

Just add your Bridging Header to imports in the Objective-C pattern, eg to import the%

#import "XMLDictionary.h"

Calling Objective-C methods in Swift

Now just use the methods, you do not have to import anything into your Swift classes, it's as simple as that!

Miscellaneous:

  • More information about this subject and source of the images on this question (in English).
  • It is interesting to follow the Xcode naming convention and naming your bridging header from $(SRCROOT) where your project is called XMLDictionary (change spaces by Meu_Projeto-Bridging-Header.h .

For completeness purposes there is the answer to the mirror question:

Using Swift class in Objective-C

Using Swift classes in Objective-C is even simpler!

If your class inherits from Meu Projeto

Just import _ into NSObject

If this file does not appear

  • In Build Settings > Packaging :
    • Mark Defines Module as Yes
    • Ensure Product Module Name contains only alpha-numeric characters
  • In Bulid Settings > Apple LLVM 6.0 - Language - Modules :
    • Enable Enable Modules (C and Objective-C) as Yes

Important : It is normal for this file not to be listed, you should be able to import it anyway.

If your class does not inherit from "MeuProjeto-Swift.h"

  • Put the Objective-C prefix before NSObject in your Swift class
  • Create a class method to be your constructor Example:

import Foundation

@objc class ObjetoSwiftPuro {

    var nome: String
    init(nome: String) {
        self.nome = nome
    }

    // Método de classe para retornar instância nova
    class func novaInstanciaNomeada(nome: String) -> ObjetoSwiftPuro {
        return ObjetoSwiftPuro(nome: nome)
    }
}

Full disclaimer: The use of Swift in Objective-C was inspired by @Logan response with @ TomášLinhart / p>     

16.01.2015 / 19:09