在 init() 中使用 guard let 安全解包可选

Safely unwrapping optional with guard let in init()

我想我可能错过了它如何工作的要点,但我有一个 class 需要在它的几个方法中使用全局可选值,现在我在每个方法中解开它,但我想我可以解开 init() 中的值。我做错了吗,或者现在它应该如何工作? - 谢谢。

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''
    }

}

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

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
    }
}