In the development of iOS apps, Swift will replace OC, the trend is "short-term coexistence, long-term replacement." But there have been too many code in the OC language, and Swift's development has inherited a lot of features from OC, and there are a lot of similarities. Swift and OC can now be seamlessly mixed-programming.
I will implement a simple swift call OC iOS instance, the implementation process is very simple. Just like all of our Hello world. The following are the steps:
(1) Create a new iOS project in Xcode, language select Swift, device select iphone. The directory structure is as follows:
(2) Then in the project right-click New File, select Cocoa Touch class, enter the class name, inherit NSObject, Language selection objective-c. After selecting Next, the first time you create an OC class in Swift, the following dialog box pops up and clicks Yes:
。
(3) After the OC class is created, the directory structure of the project is as follows: I found three more files in the directory structure, HELLO.H,HELLO.M is the OC Class I created, and so on will be called with Swift, and one is Bridging-header.h, This can be understood as bridging the file between OC and Swift.
。
(4) Then in Bridging-header.h, introduced the OC class header file, the code is: #import "Hello.h"
(5) Then in the OC class to implement a simple method, output a statement, the first declaration in Hello.h:
。
The method is then implemented using the OC syntax in HELLO.M:
。
(6) Then the method of calling OC in the Viewdidload () of Swift's class Viewcontroller.swift:
。
(7) Finally run the print result,
.
At this point, Swift can easily invoke the OC code. is not very convenient.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift and objective-c mixed programming--swift call OC