John Tseng
John Tseng

Reputation: 6352

Mixing Swift and Objective-C

I want to start a new project, but I don't know whether I should start with Objective-C or Swift. How easy is it to add Swift on top of an existing Objective-C without rewriting anything?

I see that I can mix Swift and Objective-C in the same project. Can I mix them in the same class? How about the same file?

Upvotes: 1

Views: 1851

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 186984

How easy is it to add Swift on top of an existing Objective-C without rewriting anything?

Pretty easy. XCode walks you through it when you try to add a .swift file to the project.

How about the same file?

No. A single file is a single language top to bottom.

Can I mix them in the same class?

Yes! Just like you can extend classes in ObjC, you can extend classes with Swift as well. You can write a Swift extension for an ObjC class and it works just fine.

Upvotes: 5

Undo
Undo

Reputation: 25687

It's very easy to add Swift on top of Objective-C. A great place to learn more is the Integrating Swift with Objective-C WWDC talk. You add the Obj-C classes you want Swift to be able to see to a 'bridging header'. Swift classes are automatically available to Obj-C code.

Can I mix them in the same class? How about the same file?

No. There's no support for that. A file is either Swift or Objective-C. I believe the closest you could come to having a mixed class is by writing extensions in Swift for the Objective-C class, but I haven't tried that.

Upvotes: 3

Related Questions