Objective-C and Swift

Source: Internet
Author: User

Objective-C and Swift

 

Important Materials

Using Swift with Cocoa and Objective-C official documentation

Why do we need to mix data? Language Development Trend (tietong), Swift ranking continues to rise, and OC ranking is required for normal iteration of projects
Many third-party libraries still use OC to implement the modules already implemented by OC in the project. If Swift is used to rewrite the modules, the cost is a little higher. We need to use Swift in the project to solve the problem.

Note: It is not for mixed editing. Mixed editing is only a reasonable choice after comprehensive measurement of development resources, project management and technology development trends.

How to start mixing? Procedure

Create a project. Select Swift or Objective-C for Language.

Create a Swift file and add a bridging header file

When you add a Swift file, Xcode automatically prompts you to add the bridging header file. Select Yes.

Perform two key settings


Xcode is set in both cases by default. You can change the Objective-C Bridging Header and Objective-C Generated Interface Header Name to the Name you want to set.

Now, the configuration of the Swift and Objective-C Mixed compiling environments is complete.

XXX-Bridging-Header.h

To use the OC code or library in Swift, you only needimportThe header file of the corresponding code or library.

XXX-Swift.h

Unlike XXX-Bridging-Header.h, The XXX-Swift.h file doesn't appear in the project, but is automatically generated by Xcode, you can find the corresponding project's XXX-Swift.h file in a path similar to the following: (PS: i'm sorry, I didn't write it into the PPT)

/Users/perry/Library/Developer/Xcode/DerivedData/XXX-bhlzdinkujybftbjmgwjwclndmss/Build/Intermediates/XXX.build/Debug-iphonesimulator/XXX.build/Objects-normal/x86_64/XXX-Swift.h

To use Swift code in OC#import XXX-Swift.h(PS: other notes for using Swift code in OC will be described in detail later)

View the code in the XXX-Swift.h file:

It is not hard to find that the content in this file is actually converting the code in Swift into the OC code.

Note: If you clean up the project, the file will also be deleted, and during the re-build process, this file will be regenerated only when all Swift code is compiled.

Hybrid Editing Based on the Framework

Complex Macros in OC

The Swift compiler does not contain a Preprocessor. Instead, it makes full use of the compile-time attributes to generate configurations and perform the same functions as the language features. Therefore, we recommend that you re-encapsulate the macro definition.

The macro in OC has the same name as the class in Swift.

Because Swift cannot be used#defineAnd OC can, so you may define a macro with the same name as Swift in OC. If you have never used the functions provided by Swift code in OC (that is, never#import XXX-Swift.h), There will be no problems during compilation, but if you use it, the following error will be reported:

This is because I use#define MView (@MView)SetMViewDefinedNSStringType macro, and in SwiftMViewYesUIViewIn#import MDemo-Swift.hAfter,MViewIt is repeatedly defined, leading to errors.

Update: if the class in OC has the same name as the class in Swift, this is also the case.

Swift uses the enumerated values in OC. If you only use values, you can use enumeration directly. If you need to calculate the enumerated values, you need to use .valueWhen OC uses the enumeration in Swift, it must be added before the enumeration definition in Swift. @objcThe modifier Enumeration type must be Int@ Objc/dynamic/NS * If the Swift class needs to be used in OC, it is recommended to inherit NS * series classes. If the members or methods in the Swift class need to be used in OC, use @objcModifier if the Swift class member needs to support KVC/KVO, use dynamicModifier IBOutlet vs IBOutletCollection

Not in SwiftIBOutletCollectionIs implemented in the following way:IBOutletCollection:

@IBOutlet var labels: [UILabel]!

ThisIBOutletIn the xib/Storyboard:

It should be noted that: And OCIBOutletCollectionDifferent,labelsThe elements in are not necessarily arranged in the black, white, blue, and green order!

Duplicate include

In OC, the Class A header file must contain the Class B header file, and the class B header file must also contain the Class A header file.@classTo solve the problem. However, when the class A header file in OC needs to containXXX-Swift.h, AndXXX-Bridging-Header.hZhongyouimportClass A header file, this time is awkward. See the following example:

The above example is as follows:

First, we have two Swift classes.MManagerAndMData. One OC classViewController.

Then,MManagerA Method in the class needs to be passed inViewControllerClass instance handle, and thenMDataClass instance assignedViewControllerMember variables in the class instancemData(ThismDataIsMData).

In this scenario, duplicate inclusion occurs becauseMManagerA Method in the class needs to be passed inViewControllerClass instance handleSuch a condition, so we mustXXX-Bridging-Header.hMedium#import ViewController.hIn this way, we can onlyViewController. mFile#import XXX-Swift.hTo avoid repeated inclusion. In this case, we need to set the member variablemDataDefinedidType.ViewController. mThe file is forcibly convertedMDataType. As follows:

To solve the problem of Repeated inclusion.

This processing method has the problem of member variables.mDataCan accept any type, so we need to judge when usingmDataWhether it is the data type we need. Here we will introduce how to judge Swift'sAnyObjectAnd OCidWhat type is it:

OC:

If ([self. mData isKindOfClass: [MData class]) {// if self. mData is not of the MData type, it cannot be determined}

Swift:

If let data = self. mData? MData {// If self. mData is not of the MData type, it cannot be determined}
Properties

If the OC class is imported to Swift for use, the properties of the class will change as follows:

All attributes in Swift are noatomicSo in the OC class atomicWill be invalid. getter/setterAll methods will be invalid Hello! Swift 2var-> let

Compared with Swift 1.2, Swift 2 enforces that the amount that does not change in the body of this method is declared as a constant. Therefore, you can pay attention to this point in advance when writing Swift 1.2 code, this reduces the conversion cost.

Println

This method is deleted in Swift 2. Do not use it.

Do/while-> repeat/while

We recommend that you usefor / for…inReplace

Protocol-Oriented Programming

Since Swift 2, we have been able to expand the Protocol and have officially started the protocol-Oriented Programming era of Swift. Because it has not been used in specific projects, the research is not very deep. You can refer to the following three translations:

Swift 2: Protocol-Oriented Programming

How to use the Protocol correctly

Protocol-oriented MVVM in Swift 2.0

 

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.