The road of Objective-c and Swift

Source: Internet
Author: User


This article is based on Xcode 6.4 and Swift 1.2

Important Information


Using Swift with Cocoa and OBJECTIVE-C official documentation


Why mixed?
    • Language trends (TIOBE), Swift rankings continue to rise, OC ranks gravity drop
    • Project Normal iteration needs
      • Many third-party libraries still use OC implementations
      • Modules that have already been implemented with OC in the project are slightly more expensive to rewrite with Swift
      • We need to use Swift in our projects to really run into problems and solve problems.

Note: Not for mixed and mixed. Integration is only a reasonable choice after a comprehensive measurement of development resources, project management, and technology development trends.

How do I start mixing? Steps
    1. To create a project, Language select either Swift or Objective-c.


    2. Create a Swift file and add the bridging header file


      When you add a Swift file, Xcode will automatically prompt you to add the bridging header file, select Yes

    3. Make two key settings


      Both settings Xcode is set by default, you can change the objective-c bridging header and objective-c Generated Interface header name to the name you want to set.


At this point, swift and objective-c mixed environment even if the configuration is complete.


Xxx-bridging-header.h


If you need to use the OC code or library in Swift, just the corresponding code in this fileimportor the header file of the library.


Xxx-swift.h


Unlike Xxx-bridging-header.h, the Xxx-swift.h file does not appear in the project, but is automatically generated by Xcode, and you can find the Xxx-swift.h file for the corresponding project under a path similar to the following: (PS: The presentation was not written in Ppt, Really sorry)


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


If you need to use Swift code in OC, in the file used#import XXX-Swift.h(PS: Some other considerations for using SWIFT code in OC are explained later)



To view the code in the Xxx-swift.h file:






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


Note: If the project is cleaned, the file will be deleted, and the file will be regenerated only if all Swift code is compiled through the rebuild process.

Integration of the framework




Stepping on the pit time complex macros in OC





The Swift compiler does not contain pre-processors. Instead, it takes advantage of compile-time properties, build configurations, and language features to accomplish the same functionality. Therefore, for a similar macro definition above, it is recommended to use the method to reseal once.


Macros in OC have the same name as classes in Swift


Because Swift cannot be used,#defineand OC can, so you may define a macro in OC with a similar name in Swift, if you have never used the functionality provided by SWIFT code in OC (that is, never#import XXX-Swift.h), compile without any problems, but if Use, you will report the following error:






This is because I use#define MView (@"MView")aMViewmacro that will be defined as a type, and the subclass in Swift,NSStringafter that, isMViewUIView#import "MDemo-Swift.h"MViewrepeatedly defined, resulting in an error.


Update: This is true if the class in OC and the name in Swift are similar.

Swift uses enumerations in OC
    • If you simply use a value, you can use the enumeration directly
    • If you need to perform an operation on an enumeration value, you need to use the.value
OC using enumerations in Swift
    • Need to add modifiers before Swift's enumeration definition@objc
    • The type of the enumeration must beInt
@objc/dynamic/ns*
    • If the Swift class needs to be used in OC, it is recommended to inherit the class of the Ns* series
    • If a member or method in the Swift class needs to be used in OC, use the@objcmodifier
    • If a member in the Swift class needs to support KVC/KVO, use thedynamicmodifier
Iboutlet vs Iboutletcollection


Not in SwiftIBOutletCollection, but in the following waysIBOutletCollection:


@IBOutletvar labels: [UILabel]!


TheIBOutletsituation in Xib/storyboard is as follows:






Note:IBOutletCollectionUnlike OC, the elements are not necessarily in the order oflabelsBlack,white,blue,green!


Repeat contains


OC may encounter the Class A header file needs to contain class B header files, class B header files also need to include the class A header file, this time to@classsolve the problem. But when the class A header file in OC needs to be includedXXX-Swift.h, and theXXX-Bridging-Header.himportClass A header file, this time is more embarrassing. Look at the following example:












The case of the above example is this:



First, we have two Swift classesMManagerandMData. An OC classViewController.



Then,MManagera method in the class needs to pass in a handleViewControllerto the class instance andMDataassign a class instance to aViewControllermember variable in the class instancemData(themDatatype isMData).



In this scenario, there is a duplicate inclusion, because a MManagermethod in the class has to pass in a handle toViewControllerthe class instance , so we must be inXXX-Bridging-Header.h, so#import "ViewController.h"that we can only pass the VIEWCONTROLLER.M files to#import "XXX-Swift.h"avoid duplicate inclusions in the same way. At this point we need to define the member variablemDataas aidtype, and then cast it to the type when it is used in the viewcontroller.m fileMData. As follows:









You can solve the problem of duplicate inclusion.



The problem with this approach is that member variablesmDatacan accept any type, so when we use it to determinemDataif it's the type of data we need, here's how to tell what the SwiftAnyObjectand OCidtypes are:



Oc:


if ([self.mData isKindOfClass: [MData class]]) {// If self.mData is not an MData type, the judgment is unsuccessful
} 


Swift:


if let data = self.mData as? MData {// If self.mData is not MData, the judgment is unsuccessful
} 
Properties


If the OC class is imported into Swift, the properties of the class will change as follows:


    1. The properties in Swift are allnoatomic, so the OC class will beatomicinvalidated.
    2. The overridden methods in the OC classgetter/setterare invalidated
Hello! Swift 2var Let


When you write the code for Swift 1.2, you can notice this in advance, reducing the cost of conversion, compared to the swift 1.2,swift 2 mandatory requirement to declare a value that does not change in this method body as a constant.


println


This method is removed in Swift 2 and should not be used.


Do/while-Repeat/while


Because there are changes, it is recommended tofor / for…inreplace


Protocol-oriented programming


Starting with Swift 2, we can extend the protocol and formally open the era of Swift's protocol-oriented programming. Because there is no specific use in the project, so the study is not very deep, we can refer to the following two translations:



Swift 2: Protocol-oriented programming



How to use the protocol correctly



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



The road of Objective-c and Swift


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.