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

Nullability and optionals in Objective-C

Objective-C provides a facility to work at compile time with nullability and optionals. While it's not as powerful as Swift optionals, it still provides a decent amount of safety for pure Objective-C programs. Lastly, it can be used to better interoperate with Swift.

Let's first consider this simple Objective-C interface:

@interface AnObject: NSObject

@property (nonatomic, copy) NSString* string;

@end

This is exposed in Swift as the following:

class AnObject: NSObject {
var string: String!
}

As you might notice, the string is a forced unpacked string, but this is unlikely what you would expect. Before Swift 4, the following code was valid but would crash at runtime:

// Swift 3
let object = AnObject()
let string = object.string // String!
string.appendContentsOf("SwiftObject")
//
fatal error: unexpectedly found nil while unwrapping an Optional value

Starting with Swift 4, however, the forced unpack optionals have not been accessible without using the ? operator:

// Swift 4
let object = AnObject()
let string = object.string // String!
string?.appending("SwiftObject") // safe to use

While this works properly and is now quite safe to use, this is often not what we expect to expose. Most of our objects don't have optional properties.

主站蜘蛛池模板: 资阳市| 墨竹工卡县| 高雄市| 五家渠市| 云霄县| 徐汇区| 肇东市| 广水市| 苍南县| 高淳县| 山东| 涞源县| 永顺县| 佛坪县| 金川县| 分宜县| 花莲县| 广安市| 东光县| 江永县| 天峻县| 新营市| 蓝田县| 北票市| 宿州市| 二连浩特市| 剑阁县| 嘉黎县| 博罗县| 茌平县| 黄冈市| 青阳县| 扶风县| 安徽省| 昌图县| 和平县| 平乡县| 来安县| 子长县| 咸丰县| 巴青县|