-2

Before marking this duplicate please note that I have already looked into this question How can I import Swift code to Objective-C?enter link description here but this is about importing a library,

I want to know if I can write code blocks of swift in objective C project. Or perhaps add new files/classes within the same project instead of making a separate library of swift then importing the library.

For example we can write C code in objective C in .mm files, is there a similar way to incorporate swift code in the objective C code ?

Ahmed
  • 14,503
  • 22
  • 92
  • 150

3 Answers3

3

is there a similar way to incorporate swift code in the objective C code ?

No. They are two different languages and have to go into two different files. It's the file suffix that tells the compiler what language compiler to use.

The reason it works for Objective-C in mm files is that Objective-C++ is a superset of Objective-C, which is itself a superset of C; from the Objective-C++ point of view, they are all the same language. But Swift and Objective-C are in no sense the same language.

Or perhaps add new files/classes within the same project instead of making a separate library of swift then importing the library.

Certainly. The same target can contain both Objective-C and Swift files. They just can't live in the same file.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Similarly, you could not put Objective-C into a _.c_ file. It only works the _other_ way, for the superset language, because, being a superset, they are the _same_ language. – matt May 15 '20 at 14:27
2

I want to know if I can write code blocks of swift in objective C project.

No, you can't write Swift code inside an Objective-C source file, like you can with C.

Or perhaps add new files/classes within the same project

Yes, absolutely. This is documented here.

Gereon
  • 17,258
  • 4
  • 42
  • 73
1

I want to know if I can write code blocks of swift in objective C project.

No, that's not possible. .mm files aren't Objective-C, they are Objective-C++ which is a superset of the objc language.

Or perhaps add new files/classes within the same project

This can be done, all you gonna need to do is import the Swift class that have the function you want, in the .m file. To import you gonna need a file name structure such as #import "MySwiftClassName-Swift.h". Call the functions in your .m as any objc written function. The only thing to be careful is the visibility of the functions (private swift functions will only be accessible if you have also an objective-c bridging header, the open and public swift functions will be available by default).

Carla Camargo
  • 574
  • 5
  • 14