- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 141字
- 2021-07-02 14:45:14
Using NS_ASSUME_NON_NULL_BEGIN and NS_ASSSUME_NON_NULL_END
We can use NS_ASSUME_NON_NULL_BEGIN and NS_ASSUME_NON_NULL_END in order to express broadly that all properties, method arguments, and return types are non-optional:
NS_ASSUME_NONNULL_BEGIN
@interface AnObject: NSObject
- (NSString *)sayHello; // return @”Hello World”
- (NSString *)append:(NSString *)aString with:(NSString *)anotherString;
@end
NS_ASSUME_NONNULL_END
The following snippet shows how to use it in Swift:
// Swift 5
let object = AnObject()
let string = object.sayHello() // String
let returnValue = object.append("First String", with: "Next String")
let otherString = string.appending(" From Swift") // safe to use
assert(otherString == "Hello World From Swift")
As you can see, nothing is an optional anymore and it properly expresses the need for non-optional parameters in Objective-C.
So far, we're able to mark large portions of code as non optional, but often, you'll need to mark just a few arguments or return types as optional.
推薦閱讀
- 算法競賽入門經典:習題與解答
- 數據庫基礎與應用:Access 2010
- Visual Studio 2015 Cookbook(Second Edition)
- 醫療大數據挖掘與可視化
- UDK iOS Game Development Beginner's Guide
- 大數據營銷:如何讓營銷更具吸引力
- 數據驅動設計:A/B測試提升用戶體驗
- 數據挖掘原理與SPSS Clementine應用寶典
- 云原生數據中臺:架構、方法論與實踐
- Flutter Projects
- Visual Studio 2013 and .NET 4.5 Expert Cookbook
- Web Services Testing with soapUI
- Gideros Mobile Game Development
- MySQL技術內幕:InnoDB存儲引擎
- 智能與數據重構世界