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

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.

主站蜘蛛池模板: 平度市| 巍山| 田东县| 永年县| 顺平县| 龙口市| 法库县| 湘西| 上犹县| 临武县| 勃利县| 射洪县| 田林县| 灵石县| 花莲市| 治县。| 葫芦岛市| 岗巴县| 古丈县| 蕉岭县| 桦南县| 高邑县| 湘潭市| 武城县| 十堰市| 南乐县| 金乡县| 永定县| 区。| 板桥市| 通化市| 银川市| 汨罗市| 泰州市| 灌云县| 昭通市| 淄博市| 班戈县| 民丰县| 延安市| 玛纳斯县|