swiftframeworksfatal-errorforced-unwrapping

Should I force-unwrap from a Framework?


I am building a Framework in Swift and I am not sure about the right way to deal with the following scenario.

let path = bundle.path(forResource: type.rawValue, ofType: "sks")!

As you can see I am force unwrapping the result of path(forResource:ofType:). Since I am writing the framework I know the file I am loading will always be present in the bundle. So I should not worry about the danger of the forced unwrap command.

However...

... the framework will be released as opensource.

So the developers technically will be able (even if they shouldn't) to delete the resource I am loading. In this case, of course, the previous instruction will crash the entire app.

That's why I wonder: am I following the right approach? Should I replace instead every forced unwrap instruction with a guard in order to make the framework "hack-proof"?


Solution

  • At the end of the day, I suppose it's a matter of opinion, but since this framework could potentially be used by a lot of other developers, I would try to keep it as safe as possible and use guard statements instead of force unwrapping values. I don't think you want your framework to be unintentionally responsible for crashing someone else's app, and users of the framework shouldn't have to worry about your framework doing that. Using guard doesn't hurt anything, as the resource should always be there, but on the off chance that it gets deleted by accident you can always print something on the console for the developer to read, or throw an error.

    enum ErrorHandler: Error {
        case resourceDoesNotExist
    }
    
    func getPath() throws -> String{
    
        guard let path = bundle.path(forResource: type.rawValue, ofType: "sks") else {
            throw ErrorHandler.resourceDoesNotExist
        }
        return path
    }
    

    That's a really basic example, but hopefully you get the gist. Here's Apple documentation for error handling if you want to read more: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html