- 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.
- 企業數字化創新引擎:企業級PaaS平臺HZERO
- Game Development with Swift
- 文本數據挖掘:基于R語言
- 業務數據分析:五招破解業務難題
- 基于Apache CXF構建SOA應用
- MySQL技術內幕:SQL編程
- 貫通SQL Server 2008數據庫系統開發
- Internet of Things with Python
- MySQL技術內幕:InnoDB存儲引擎
- 利用Python進行數據分析(原書第2版)
- Swift Functional Programming(Second Edition)
- Delphi High Performance
- 代碼的未來
- Trino權威指南(原書第2版)
- Redis 6開發與實戰