【问题标题】:Safely unwrapping optional with guard let in init()在 init() 中使用 guard let 安全地展开可选
【发布时间】:2019-09-24 22:30:28
【问题描述】:

我想我可能错过了它的工作原理,但是我有一个类需要在它的几个方法中使用全局可选值,现在我在每个方法中解包它,但我想我可以解包值在初始化()中。我做错了还是现在应该如何工作? - 谢谢。

let iCloudPath = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")


class iCloudManager {

    init() {
        guard let iCloudPath = iCloudPath else { return }
    }

    function1(){
        // uses iCloudPath but returns 'Value of optional type 'URL?' must be unwrapped to a value of type 'URL''
    }

    function2(){
        // uses iCloudPath but returns 'Value of optional type 'URL?' must be unwrapped to a value of type 'URL''
    }

}

【问题讨论】:

  • nil 的返回值在这里究竟是什么意思?

标签: swift function optional init guard


【解决方案1】:

将结果存储为对象的属性。更好的是,使用静态属性,而不是全局属性。

class iCloudManager {
    static let defaultPath = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")

    let path: URL

    init?() {
        guard let path = iCloudManager.defaultPath else { return nil }
        self.path = path
    }

    func function1() {
        // uses self.path
    }

    func function2() {
        // uses self.path
    }
}

【讨论】:

  • 嗨,Alexander,感谢您回答我的另一个问题。你愿意告诉我更多关于它是如何工作的吗?如果值为 nil,返回 nil 不会导致应用程序崩溃吗?要回答您的评论,如果由于某种原因 iCloud 容器或文档文件夹不存在,那将是 nil。我确实检查了设备上是否启用了 iCloud,如果容器中不存在文档文件夹,我有一种方法来创建它,但你永远不知道。
  • @CristianMoisei 这是一个可选的初始化器,注意init?。因此,如果您执行let foo = iCloudManager() 并且路径为零,那么foo 将为零。
  • "如果值为 nil,返回 nil 是否会导致应用程序崩溃?"没有。这被称为“失败的初始化程序”。它返回一个iCloudManager?,而不是通常的iCloudManager。只有当你告诉它在nil 上崩溃时它才会在nil 上崩溃(通过! 强制解包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 2016-10-29
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 2017-07-16
相关资源
最近更新 更多