Search code examples
swiftfunctionoption-typeinitguard

Safely unwrapping optional with guard let in init()


I think I probably missed the point of how this works but I have a class that needs to use a global optional value in several of its methods and right now I unwrapped it inside every method but I thought I could just unwrap the value in init(). Am I doing it wrong or is this now how it's supposed to work? - Thank you.

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

}

Solution

  • Store the result as a property of your objects. Better yet, use a static property, not a global.

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