Use Swift and objective-c in the same project (Swift 2.0 update)-B

Source: Internet
Author: User
Tags custom name

This section contains content:

    • Mix and Match overview (mix and Match overview)

    • Import in target of the same app (importing Code from within the same app target)

    • Import from Target in the same Framework (importing Code from within the same Framework target)

    • Import external Framework (importing External frameworks)

    • Using Swift in Objective-c (using Swift from OBJECTIVE-C)

    • Rewrite the Swift name for the Objective-c interface

    • Product modules naming (naming Your product module)

    • Problem solving tips (troubleshooting tips and Reminders)

Swift's compatibility with objective-c allows you to use both languages in the same project. You can use this feature called mix and match to develop a hybrid language-based application that can implement part of the app's functionality with the latest features of Swift and seamlessly incorporate into existing objective-c code.
Mix and Match Overview

Objective-c and Swift files can coexist in a project, whether the project was originally based on objective-c or Swift. You can simply add a source file for another language directly to an existing project. This natural workflow makes it easy to create a mixed-language application or framework target, as in a single language.

The workflow of a mixed language is only a little bit different, depending on whether you are writing the application or writing the framework. The following describes the normal use of two languages in a target to import the model, the subsequent chapters will have more details.

Import in target of the same app

If you are writing a mixed-language application, you may need to access the OBJECTIVE-C code with Swift code, or vice versa. The following procedure describes the application in non-frame target.

Import Objective-c to Swift

When importing some objective-c files for use by Swift code in an app's target, you need to rely on Objective-c's Bridge header file (bridging header) to expose to Swift. When you add Swift files to an existing Objective-c app (or vice versa), Xcode automatically creates the header files.

If you agree, Xcode generates a header file at the same time that the source file was created and is named with the product's module name plus-bridging-header.h. For the module name of product, see Naming Your product module.

You should edit this header file to expose the Objective-c code to Swift.

Import objective-c code into Swift in the same target

1. In the Objective-c Bridge header file, import any header files you want to expose to Swift, for example:

123 #import "XYZCustomCell.h"#import "XYZCustomView.h"#import "XYZCustomViewController.h"

2. Make sure that the build setting of the Objective-c Bridge header file in Build Settings is based on the Swfit compiler, which is the path where the Code Generation contains the header file. This path must be the path of the header file itself, not the directory in which it resides.

This path should be the relative path to your project, similar to the path specified by Info.plist in Build Settings. In most cases, you do not need to modify this setting.

All public objective-c header files listed in this bridge connector file will be visible to Swift. All Swift files for the current target can then use the methods in these header files without any import statements. Use the OBJECTIVE-C code in swift syntax just as you would with a swift class that comes with your system.

12 let myCell = XYZCustomCell()myCell.subtitle = "A custom cell"

Import Swift into Objective-c

When you import Swift code into OBJECTIVE-C, you rely on the header files generated by Xcode to leak these files to objective-c. This auto-generated file is a objective-c header file that contains all the interfaces defined in the Swift code in your target. You can think of this objective-c header file as the umbrella header of the Swift code. The header file name is named with the product module name plus-swift.h. (for the module name of product, see naming Your product module).

By default, the generated header file contains a Swift declaration interface marked with the public modifier. It also contains those that hit if your application's target has a OBJECTIVE-C bridge connector internal modification. The declaration marked with the private modifier does not appear in the generated header. Private statements do not come into contact with objective-c unless they are clearly marked with @ibaction, @IBOutlet, or @objc as well. If the goal of your application is to compile the test to enable, the unit test target can access any declarations with the internal adornments, as if they were imported with the public modifier through the pre-@testable product module of the statement declaration.

You don't need to do anything to generate this header file, just import it into your objective-c code to use it. Note that the Swift interface in this header file contains all the objective-c types that it uses. If you use your own objective-c type in swift code, be sure to import the corresponding Objective-c header file into your swift code before importing the Swift Auto-generated header file into the objective-c. m source file to access S Wift code.

Import Swift code into objective-c in the same target

    • In the objective-c. M source file of the same target, use the following syntax to import the SWIFT code:

1 #import "ProductModuleName-Swift.h"

Any Swift file in target will be visible to the objective-c. m source file, including this import statement. For the use of Swift code in OBJECTIVE-C code, see Using Swift from Objective-c.

Import in target of the same Framework

If you are writing a mixed language framework, you may be able to access the OBJECTIVE-C code from the Swift code, or vice versa.

Import Objective-c to Swift

To import some objective-c files into the Swift code of the same frame target, you need to import these files into the Objective-c umbrella header for the framework to use.

Import objective-c code into Swift in the same framework

Make sure that the Build Settings > Packaging > Defines Module of the framework target is set to Yes. Then import the objective-c header file that you want to expose to Swift access in your umbrella header file, for example:

1 #import #import #import

Swift will see all the header files you expose in the umbrella header, and all swift files in the framework target can access the contents of your objective-c file without any import statements.

12 let myCell = XYZCustomCell()myCell.subtitle = "A custom cell"

Import Swift into the Objective-c

To import some swift files into the objective-c code of the target of the same framework, you do not need to import anything into the umbrella header file, but instead import Xcode into your Obj. M source for your swift code auto-generated header file. File to access the Swift code in the OBJECTIVE-C code.

Import Swift code into OBJECTIVE-C in the same framework

Make sure that the defines Module in Build Settings > Packaging of the framework target is set to Yes. Use the following syntax to import the Swift code into the objective-c. m source file under the same framework target.

12 // OBJECTIVE-C#import

The import statement contains Swift files that can be accessed by the objective-c. m source file under the same framework target. For the use of Swift code in OBJECTIVE-C code, see Using Swift from Objective-c.

Import External Framework

You can import an external framework, whether it's pure objective-c, pure Swift, or mixed language. The process of import external frames is the same, whether the framework is written in one language or two languages. When you import an external frame, make sure that Build Setting > pakaging > Defines Module is set to Yes.

Use the following syntax to import the framework into Swift files of different target:

1 import FrameworkName

Use the following syntax to import the framework into the objective-c. m file for different target:

1 @import FrameworkName;

Using Swift in Objective-c

After you import the SWIFT code into OBJECTIVE-C, you can use the Swift class with the regular objective-c syntax.

12 MySwiftClass *swiftObject = [[MySwiftClass alloc] init];[swiftObject swiftMethod];

Swift's class or protocol must be marked with a @objc attribute to be accessible in objective-c. This property tells the compiler that this Swift code can be accessed from the OBJECTIVE-C code. If your Swift class is a subclass of the Objective-c class, the compiler will automatically add @objc for you. See Swift Type compatibility.

You can access any object marked with the @objc property in a Swift class or protocol, as long as the object is compatible with Objective-c. Does not include the following Swift-exclusive features:

    • Fan type (generics)

    • Tuples (tuples)

    • Enumerations defined in Swift do not include an int primitive value type (enumerations defined in swift without int raw value type)

    • Structural bodies defined in SWIFT (structures defined in swift)

    • Top-level functions defined in SWIFT (top-level functions defined in swift)

    • Global variables defined in SWIFT (Globals variables defined in swift)

    • Type aliases defined in Swift (typealiases defined in Swift)

    • Swift style variable parameters (Swift-style variadics)

    • Nested types (Nested types)

    • Curry function (curried functions)

For example, a method that uses a generic type as a parameter or returns a tuple cannot be used in objective-c.

Note that you cannot inherit a Swift class in Objective-c.

Referencing the Swift class in the Objective-c header file

This way forward declares the Swift class:

1234567 // OBJECTIVE-C// MyObjective-CClass.h@class MySwiftClass;@interface MyObjective-CClass : NSObject- (MySwiftClass *)returnSwiftObject;/* ... */@end

Rewrite the Swift name for the Objective-c interface

The Swift compiler automatically imports the OBJECTIVE-C code as a regular Swift code. It imports the Objective-c class factory method as a Swift constructor and truncates the enumeration type name of the objective-c.

There may be boundary conditions in your code that cannot be handled automatically. If you need to change the Objective-c method, enumeration, or optional set value that is imported into Swift, you can use the Ns_swift_name macro to customize the imported declaration.

Class Factory method

If the Swift compiler does not recognize the class factory method, you can use the Ns_swift_name macro to correctly import the swift signature of the constructor. For example:

1 + (instancetype)recordWithRPM:(NSUInteger)RPM NS_SWIFT_NAME(init(RPM:));

If the Swift compiler incorrectly recognizes a method as a class factory method, you can use the Ns_swift_name macro to correctly import the swift signature of the constructor. For example:

1  (id)recordWithQuality:(double)quality NS_SWIFT_NAME(record(quality:));

Enumeration

By default, Swift truncates the name prefix of the enumeration value to import the enumeration. If you want to customize the name of an enumeration value, you can use the Ns_swift_name macro to pass the SWIFT enumeration value name. For example:

1234 typedef NS_ENUM(NSInteger, ABCRecordSide) {  ABCRecordSideA,  ABCRecordSideB NS_SWIFT_NAME("FlipSide"),};

Product module naming

The name of the header file generated by Xcode for Swift code, and the name of the Objective-c Bridge Connector file created by Xcode, are generated from your product module name. By default, your product module name is the same as the product name. However, if your product name has special characters (nonalphanumeric, non-numeric, alphabetic characters), such as the dot, then they will be replaced by an underscore (_) as your product module name. If the product name starts with a number, the first number is replaced with an underscore.

You can provide a custom name for the product module name that Xcode uses to name the bridged and automatically generated header files. You only need to modify the Product Module Name in the build setting.

Problem Resolution Tips

    • Think of Swift and objective-c files as the same Code collection, with attention to naming conflicts.

    • If you use the framework, make sure that the defines module compilation settings under packaging are set to Yes.

    • If you use the Objective-c Bridge header file, make sure that the Objective-c Bridge header file in the Swift compiler is compiled with code generation that has a path to the project-related header file. This path must be the path of the header file itself, not the directory in which it resides.

    • Xcode uses the name of your engineering module instead of naming the Objective-c Bridge header file with the name of target and the auto-generated header file for Swift code. See Naming Your Product Module.

    • In order to be available in Objective-c, the Swift class must be a subclass of the Objective-c class or be marked with a @objc.

    • When you import swift into Objective-c, remember that OBJECTIVE-C does not convert the features that are unique to swift into OBJECTIVE-C counterparts. See list Using Swift from Objective-c.

    • If you use your own objective-c type in swift code, be sure to import the corresponding Objective-c header file into your swift code before importing the Swift Auto-generated header file into the objective-c. m source file to access S Wift code.

    • Swift claims marked with the private modifier do not appear in the auto-generated header file. Private claims do not leak to objective-c unless they are clearly marked with @ibaction, @IBOutlet, or @objc.

    • For app targets, if there is a objective-c bridge header file, the declaration labeled by the internal modifier appears in the auto-generated header file.

    • For frame targets, only declarations marked with the public modifier appear in the auto-generated header file. You can still use Swift methods and properties that are marked with the internal modifier in the OBJECTIVE-C section of the framework, as long as the class where they are declared inherits from the Objective-c class. For more information about access level modifiers, see Access Control in the Swift programming language

Use Swift and objective-c in the same project (Swift 2.0 update)-B

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.