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

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.

主站蜘蛛池模板: 三原县| 咸丰县| 晋州市| 盐津县| 丰镇市| 金沙县| 平舆县| 奎屯市| 安岳县| 翼城县| 临沧市| 山东省| 昌宁县| 灵丘县| 股票| 鸡西市| 怀仁县| 浙江省| 延庆县| 陈巴尔虎旗| 邯郸县| 崇义县| 东丽区| 招远市| 寿光市| 绥芬河市| 邢台县| 青岛市| 高平市| 乐平市| 根河市| 萍乡市| 大悟县| 淮滨县| 平潭县| 长顺县| 句容市| 垫江县| 卢氏县| 阿坝| 繁昌县|