Objective-C: The Path to Swift mixing, objective-cswift

Source: Internet
Author: User

Objective-C: The Path to Swift mixing, objective-cswift

This article is based on Xcode 6.4 and Swift 1.2.

Important Materials

Using Swift with Cocoa and Objective-C official documentation

Why do we need to mix data?
  • Language Development Trends, Swift rankings continue to rise, and OC rankings are declining by gravity
  • Normal project iteration needs
    • Many third-party libraries are still implemented using OC
    • If the module originally implemented with OC in the project is rewritten with Swift, the cost is slightly 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

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.h"After,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.

Enumeration in Swift using OC
  • If you only use values, you can use enumeration directly.
  • Use.value
OC uses enumeration in Swift
  • Before the enumeration definition of Swift, add@objcModifier
  • The enumerated type must beInt
@ Objc/dynamic/NS *
  • If the Swift class needs to be used in OC, we recommend that you inherit the class of NS * series.
  • If the members or methods in the Swift class need to be used in OC, use@objcModifier
  • If members of the Swift class need to support KVC/KVO, usedynamicModifier
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.h"In this way, we can onlyViewController. mFile#import "XXX-Swift.h"To 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:

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

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.