- 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.
- Modern Programming: Object Oriented Programming and Best Practices
- Python數(shù)據(jù)分析、挖掘與可視化從入門到精通
- MySQL基礎(chǔ)教程
- 數(shù)據(jù)庫開發(fā)實(shí)踐案例
- 大數(shù)據(jù):規(guī)劃、實(shí)施、運(yùn)維
- 大話Oracle Grid:云時(shí)代的RAC
- 重復(fù)數(shù)據(jù)刪除技術(shù):面向大數(shù)據(jù)管理的縮減技術(shù)
- INSTANT Apple iBooks How-to
- Google Cloud Platform for Developers
- 區(qū)塊鏈技術(shù)應(yīng)用與實(shí)踐案例
- 智慧城市中的大數(shù)據(jù)分析技術(shù)
- Deep Learning with R for Beginners
- 離線和實(shí)時(shí)大數(shù)據(jù)開發(fā)實(shí)戰(zhàn)
- 數(shù)據(jù)挖掘與機(jī)器學(xué)習(xí)-WEKA應(yīng)用技術(shù)與實(shí)踐(第二版)
- Artificial Intelligence for Big Data