ios - 在 Swift 中使用 if let 语法解开双可选(Type?)?

标签 ios swift option-type

如果我尝试编译以下代码,它将在 print 上失败线。

func foo(application: UIApplication) {
    if let window = application.delegate?.window {
        print(window.frame) // SYNTAX ERROR
    }
}

原因是窗口类型为UIWindow? ,不是UIWindow :

error: value of optional type 'UIWindow?' not unwrapped; did you mean to use '!' or '?'?

我可以通过这样做来修复它:

func foo(application: UIApplication) {
    if let window = application.delegate?.window {
        if let window = window {
            print(window.frame)
        }
    }
}

但是,这会增加更多行代码,而且似乎没有必要。我以为if let <variable> = <value>应该只执行它的主体如果 window发现不是nil .

换句话说,我希望它会使用这种逻辑:

  • 如果application.delegate = nil ,不执行该 block 。
  • 如果application.delegate.window = nil ,不执行该 block 。
  • 如果application.delegate.window != nil ,执行该 block 并允许我使用 window作为非可选UIWindow .

为什么是if let window = application.delegate?.window定义window作为可选的?有什么方法可以通过添加很少的代码或不添加代码来让它表现得像上面的第二个代码片段一样?

注意:我不想使用 print(window?.frame)因为打印只是一个例子。我实际上有更多的代码,并且不想使用空对象模式。我希望它真正被定义为非可选。

更新:如果我使用 let test = application.delegate?.window ,我看到类型是 UIWindow?? ,或双重可选。这解释了为什么我确实需要第二个 let 语句。所以我想我现在的问题是解开双可选的最简洁的方法是什么?

最佳答案

一种可能的解决方案...

if let window = application.delegate?.window ?? nil {
  print(window.frame)
}

关于ios - 在 Swift 中使用 if let 语法解开双可选(Type?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815012/

相关文章:

ios - 应用内购买下载期间设备用尽了磁盘空间

ios - 在另一个 Swift 方法中访问 let/var

scala - 可以更简洁地使用 Scala 的 Option flatMap 方法吗?

php - 使用 JSONmodel 尝试从服务器获取数据到 ios 设备

ios - 快速创建 Sprite 套件游戏。将角色添加到场景中

objective-c - iOS - 文本字段到 int 变量

ios - AVD_loader.cpp : failed to get a service for display 4

ios - ios 如何退出谷歌账户?

swift - 如何为 UIViewController 自定义子类创建非可选存储属性

swift - 关于在 Swift 中声明可选项和非可选项