- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 201字
- 2021-07-02 14:45:14
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.
- 大數據技術基礎
- 數據庫原理及應用教程(第4版)(微課版)
- Mastering Ninject for Dependency Injection
- 計算機信息技術基礎實驗與習題
- Microsoft Power BI數據可視化與數據分析
- 數據庫設計與應用(SQL Server 2014)(第二版)
- Oracle RAC日記
- 企業主數據管理實務
- 計算機視覺
- 數據分析思維:產品經理的成長筆記
- Arquillian Testing Guide
- 一類智能優化算法的改進及應用研究
- 算力芯片:高性能CPU/GPU/NPU微架構分析
- 從零進階!數據分析的統計基礎(第2版)
- Managing Software Requirements the Agile Way