David
David

Reputation: 402

I've tried it all, but I can't import my Swift file to my Objective-C file

I've read though multiple threads on this on StackOverflow, and I can't seem to find the answer to my problem. My folder hierarchy is like this:

"Project Name" - "Helpers" "FileIWantToImport.swift" "FileIWantToImportTo.m"

I have:

HOWEVER. I cannot, for the life me, figure out why it won't import into FileIWantToImportTo.m

I have tried:

All I get is "file not found" error. Can someone please point me in the right direction? I've looked through all the other threads and the apple docs and can't figure it out. I'm running in Xcode 7 and 10.11 GMs if that makes a difference.

EDIT: Here is an example project https://github.com/Aghassi/Example-Project

Upvotes: 2

Views: 1603

Answers (1)

lucaslt89
lucaslt89

Reputation: 2451

This is what you need to do:

  1. Create a Swift file in your ObjC based project. No need to create bridging headers, since they're used to see ObjC code from swift, not swift code from ObjC.

  2. In your Target, under Build Settings set Embedded Content Contains Swift Code to Yes

enter image description here

  1. Your Swift file should have an @objc public class.

    @objc public class Example: NSObject {
        public func printSomething(text: String) {
            print(text);
        }
    }
    
  2. Check your Project's name, and in your .m file, add #import <ProjectsName-Swift.h>, and you should be able to instantiate your class defined in the Swift file, and all it's public methods. You might need to build your project before importing the -Swift.h file.

Here's an example project with an ObjC class using Swift code: https://github.com/lucaslt89/Example-Project.git

Upvotes: 3

Related Questions