Swiftlint allow force unwrap for hardcoded URLs while maintaining force_unwrapping rule

265 views Asked by At

In my iOS porjects i use Swiftlint with the rule "force_unwrapping". But every time i need to hardcode a URL i'd like to simply force unwrap it.

Is there a configuration for Swiftlint to allow such cases? Currently i simply disable and re-enable the rule around this code.

Link("Google", destination: URL(string: "https://www.google.com)")!) // throws force_unwrapping warning
1

There are 1 answers

2
Sulthan On BEST ANSWER

The trick is to put the unwrapping to a single place and disable swiftlint on that single place:

For example:

public extension URL {
    init(safeString: String) {
        // swiftlint:disable:next force_unwrapping
        self.init(string: safeString)!
    }
}

Then you can use URL(safeString: "https://www.google.com") without problems. Of course, you don't need to necessarily use forced unwrapping, you could also throw a fatalError.

However, note that with expression macros coming in Swift 5.9 (Xcode 15), you can actually write a macro that will validate your URL at compilation time, e.g.

#URL("https://swift.org/")

You can find it in swift-macro-examples repo.