Objective-C calls Swift and objective-cswift

Source: Internet
Author: User

Objective-C calls Swift and objective-cswift

If you already have an old iOS app, it is written in Objective-C, and some of its new features need to be written in Swift, then you can call Swift from Objective-C.

Objective-C does not need to bridge the header file when calling Swift, but needs the header file generated by Xcode. This type of file is generated by Xcode and does not require maintenance. It is invisible to developers. As shown in, it can expose the classes in Swift to Objective-C. Its name is: <Project Name>-swift. h. We need to introduce this header file into the Objective-C file, and the class in Swift needs to be declared as @ objc.

Create an Objective-C Project

To better introduce mixed call, we first create an Objective-C Project. For the sake of simplicity, we can create a Mac OS X command line project.

Start Xcode 6, and click File → New → Project menu, on the open Choose atemplate for your new project page, select the "OS X → Application → Command Line Tool" project template (as shown in ).


Click "Next". The page shown in is displayed.


Enter "HelloWorld" in the Product Name and select "Objective-C" in the Language. Other projects can input content based on their actual conditions. After setting related project options, click "Next". The subsequent steps are similar.

As shown in the figure below, a main. m file is generated in the left-side navigation pane. Open the main. m file and you can see its code in the Code interface on the right. We can also write code here.


Add Swift class in the Objective-C Project

We have just created an Objective-C Project and need to add the Swift class to the project. Right-click the HelloWorld group and select "New File…" from the menu ..." The create file template dialog box is displayed. As shown in, choose OS X → Source → Cocoa Class.


Click "Next". The page shown below is displayed. Enter "SwiftObject" in the Class and select Swift in the Language. You can leave the default value for other options.


After setting the related options, click "Next" to go to the Save file page. Select the file storage location as prompted, and then click "Create" to Create a Swift class. If there is no bridging header file in the project, Xcode will also prompt whether to add the bridging header file during creation. You can choose not to add it.

Call Code

After Swift's SwiftObject is created, we will see the newly added SwiftObject. swift file in the Xcode project.

The swift code is as follows:

 

import Foundation                                                               ① @objc class SwiftObject: NSObject {                     ② Func sayHello(greeting : String, withName name : String) ->String {      ③ var string = "Hi," + namestring += greeting return string;    }}

Line ① Of the above Code introduces the header file of the Foundation framework. Line ② defines the SwiftObject class, And the SwiftObject class inherits from the NSObject class. In addition, we declare @ objc before the class, and the class declared by @ objc can be accessed by Objective-C, and @ objc can also modify attributes.

The Code in line ③ defines the sayHello method, which has two parameters. The first parameter does not need to specify the external parameter name, and the second parameter (except for all parameters after the first parameter) you need to specify the external parameter name. For example, withName is the External Parameter name of the name parameter. This is to facilitate calling in Objective-C.

The following shows the Objective-C code. The main. m file code is as follows:

#import <Foundation/Foundation.h>#import "HelloWorld-swift.h"                            ① int main(intargc, const char * argv[]) { SwiftObject *sobj = [[SwiftObjectalloc] init];          ②NSString *hello = [sobjsayHello:@"Good morning"withName:@"Tony"];        ③ NSLog(@"%@",hello);                                                         ④ return 0;}

Line ① Of the above Code introduces the header file HelloWorld-swift.h, which is required for Objective-C to call Swift objects and Its naming rule is "<Project Name>-swift. h ".

Line ② instantiate the SwiftObject object, and SwiftObject is the class defined in Swift. The Code in line ③ calls the sayHello method of SwiftObject. Shows the correspondence between the methods and parameter names used in Objective-C and the methods and parameters of SwiftObject.

 


Line ④ NSLog (@ "% @", hello) is used to output the result. The output result is as follows:

14:25:43. 879 HelloWorld [3266: 303] Hi, TonyGood morning

In this way, the Swift code is called in Objective-C. We can use this method to make full use of the existing Swift files to reduce code duplication and improve work efficiency.


For more information, please refer to the first domestic Swift book "Swift development guide" for discussion. Website: http://www.51work6.com/swift.phpwelcome to the swifttechnology discussion group: 362298.pdf

Welcome to Zhijie iOS public classroom Platform




There is no need to learn objective-c when Apple launches Swift.

No, according to apple, Swift is superior to objective-c in all aspects. Since it is better, why do we need to learn Old and low performance?
The advantage of objective-c is maturity, but maturity cannot cover up its shortcomings. Although Swift is young, it may have great potential (whether it has great potential to develop with apple ), after all, it only applies to apple
If you focus on apple development, it is better to learn Swift directly. It is easy to learn one course first, even if needed. For the moment, Swift has few materials, but as long as you have the perseverance to learn, this should not be a problem. Besides, what can you worry about?

To learn the swift language, do you need to learn objective-c?

Clearly tell you: No.

Swift was developed by Apple to replace ObjC. If he still needs to have the ObjC foundation for learning, it would be so sad...
Furthermore, it is easier for a novice programmer to learn swift than other programming languages.

I hope my answer will help you! ^ O ^

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.