官术网_书友最值得收藏!

Exposing Swift to Objective-C

In order to expose Swift to Objective-C, Xcode will generate a header for you, which contains all Swift classes and modules that can be exposed to Objective-C. In Xcode, you can set the value of that header by controlling SWIFT_OBJC_INTERFACE_HEADER_NAME.

There are many reasons why a Swift class can't be exposed to Objective-C, including the following:

  • Using types that don't directly bridge to Objective-C
  • Using generics
  • Using pure Swift structs and classes

SWIFT_OBJC_INTERFACE_HEADER_NAME is usually set to $(SWIFT_MODULE_NAME)-Swift.h at the project level, which is a good default and unlikely to conflict with any other header declaration. Most of the time, $(SWIFT_MODULE_NAME) will be the name of your app.

Whenever you need to import Swift code in your Objective-C implementation files use the following:

#import "MyProject-Swift.h"

This will properly import all of your Objective-C compatible declarations from Swift. 

Now that we have properly bridged the two worlds of Swift and Objective-C, let's explore the interoperability layer with one of the most important features of Swift, nullability. In Objective-C, sending a message to nil or calling a method on a nil object has no effect, but it's unlikely that the developer on purpose left that in the code. Unlike Java, the program will not crash, nor raise an exception. In Swift, calling a method on a nil value results in a crash. As Objective-C can produce nil values, we need to reconcile these two worlds with nullability annotations.

主站蜘蛛池模板: 陆河县| 久治县| 浦江县| 泗阳县| 驻马店市| 开化县| 资源县| 中宁县| 靖安县| 疏附县| 洮南市| 桐乡市| 探索| 宜丰县| 从化市| 聂荣县| 凉山| 凤城市| 石门县| 新兴县| 南溪县| 惠东县| 武穴市| 天台县| 扎兰屯市| 会宁县| 吉木萨尔县| 田阳县| 孟津县| 长丰县| 柳林县| 河北省| 阿拉善左旗| 漳平市| 抚宁县| 雷山县| 河池市| 新民市| 饶平县| 彰武县| 巴东县|