Tuesday, May 31, 2016

Migrating Objective C code to Swift


Migration provides an opportunity to revisit an existing Objective-C app and improve its architecture, logic, and performance by replacing pieces of it in Swift. For a straightforward, incremental migration of an app, you’ll be using the tools learned earlier—mix and match plus interoperability. Mix-and-match functionality makes it easy to choose which features and functionality to implement in Swift, and which to leave in Objective-C. Interoperability makes it possible to integrate those features back into Objective-C code with no hassle.

The most effective approach for migrating code to Swift is on a per-file basis—that is, one class at a time. Because you can’t subclass Swift classes in Objective-C, it’s best to choose a class in your app that doesn’t have any subclasses. You’ll replace the .m and .h files for that class with a single .swift file. Everything from your implementation and interface goes directly into this single Swift file. You won’t create a header file; Xcode generates a header automatically in case you need to reference it


Below are the steps

1) Create a Swift class for your corresponding Objective-C .m and .h files by choosing File > New > File > (iOS, watchOS, tvOS, or OS X) > Source > Swift File. You can use the same or a different name than your Objective-C class. Class prefixes are optional in Swift.
2) Import relevant system frameworks.
3) Fill out an Objective-C bridging header if you need to access Objective-C code from the same app target in your Swift file.
4) To make your Swift class accessible and usable back in Objective-C, make it a descendant of an Objective-C class. To specify a particular name for the class to use in Objective-C, mark it with @objc(name), where name is the name that your Objective-C code uses to reference the Swift class.

references:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/Migration.html

No comments:

Post a Comment