user57213 user57213 - 7 months ago 22
Swift Question

What to return when a NSURL results in nil

I have a static function which just reads a security scoped bookmark from NSUserdefaults. Like this:

static func desktopURL()->NSURL {
let desktopData = NSUserDefaults.standardUserDefaults().dataForKey("desktopSecurityBookmark")
if (desktopData != nil){
let desktop = try! NSURL(byResolvingBookmarkData: desktopData!, options: NSURLBookmarkResolutionOptions.WithSecurityScope, relativeToURL: nil, bookmarkDataIsStale: nil)
desktop.startAccessingSecurityScopedResource()
return desktop
} else {
// what the heck to return when URL was not set in the first place??
let desktopNil = NSURL() // :D ??? I need to return at leas something or not?
return desktopNil
}
}


I mean I need to return at least something or not?

Answer

The best way to deal with these situations is to make your return type optional, then you can return nil if your desktopData is nil. It is usually easier to handle the logic for a nil response in the function calling this function

Eg

static func desktopURL() -> NSURL? {
    let desktopData = NSUserDefaults.standardUserDefaults().dataForKey("desktopSecurityBookmark")
    if (desktopData != nil){
        let desktop = try! NSURL(byResolvingBookmarkData: desktopData!, options: NSURLBookmarkResolutionOptions.WithSecurityScope, relativeToURL: nil, bookmarkDataIsStale: nil)
        desktop.startAccessingSecurityScopedResource()
        return desktop
    } else {
        return nil 
    }
}