Skip to main content
 首页 » 操作系统

ios之为什么我们在swift中给可选值赋值时忽略感叹号

2024年01月01日49bluestorm

var window: UIWindow? 
 
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { 
    // Override point for customization after application launch. 
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds) 
    self.window!.backgroundColor = UIColor.whiteColor() 
    self.window!.makeKeyAndVisible() 

在这段代码中,我们初始化了一个可选的UIWindow?。要为它赋值,我假设我会将值赋给 self.window!,因为这是可选值所在的位置。但是如您所见,我们需要使用 self.window。为什么会这样。为什么注释下第一行不像self.window! = UIWindow(frame: ....

请您参考如下方法:

感叹号用于强制展开可选值。在您的代码中,window 尚未定义,尝试强制展开它会引发错误。

来自 The Swift Programming Language Guide

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.