"Learn Swift from Scratch" Study Notes (Day 70) - Swift and Objective-C API Mapping of Swift and Objective-C Mixed Programming

Original article, welcome to reprint. Please indicate: Guan Dongsheng's blog 

 

Swift and Objective-C API mapping

 

In the mixed programming process, Swift and Objective-C calls are bidirectional. Since different languages ​​express the same API differently, there is a certain mapping rule between them. This API mapping rule is mainly reflected in constructors and methods. two aspects. 

 

1. Constructor mapping

 

When Swift and Objective-C are mixed programming, the first thing involves calling the constructor to instantiate the object. Different languages ​​have different expressions of the constructor. The picture shows the official API document of Apple, which describes a constructor of the NSString class.

 

 

 

Except for the first parameter of the Swift constructor, the external names of the other parameters are the names of the corresponding parts of the selector. Other details of the law have been clearly explained in the figure, and this law is also vice versa, so it will not be repeated here.

 

 

  

2. Method name mapping

 

When Swift and Objective-C are used for mixed programming, the method names are expressed differently in different languages. The picture shows the official API document of Apple , which describes the rangeOfString:options:range: method of the NSString class .

 

 

 

The first part of the selector, rangeOfString , is used as the method name. In general, the external parameter name of the first parameter of a Swift method is to be omitted. The " _ " symbol indicates omission. The names of the parts of the selector after it (such as options and range ) are used as external parameter names. In addition to the parameter name corresponding to, the parameter type should also be corresponding.

  

 

After Swift 2.0 , methods can declare throwing errors. These methods can throw errors. The method name representation in different languages ​​is shown in the figure below, which is writeToFile:atomically:encoding:error: Apple's official API document.

 

 

 

 

Comparing the two different languages, we will find that the error parameter is no longer used in the Swift language, but the throws keyword is added after the method.

 

This mapping rule applies not only to the Objective-C classes officially provided by Apple , but also to the Objective-C classes written by yourself .

 

 

 

  

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326990433&siteId=291194637