Skip to content

Instantly share code, notes, and snippets.

@liamnichols
Created July 10, 2020 06:52
Show Gist options
  • Save liamnichols/99ff878ce7d752e467c7b02f804242ce to your computer and use it in GitHub Desktop.
Save liamnichols/99ff878ce7d752e467c7b02f804242ce to your computer and use it in GitHub Desktop.
A non-failable initialiser extension for URL that accepts StaticString
import Foundation
extension URL {
/// Initialize with a static string.
///
/// If the `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string), a precondition failure will trigger at runtime.
init(staticString: StaticString) {
guard let url = Self.init(string: String(describing: staticString)) else {
preconditionFailure("'\(staticString)' does not represent a legal URL")
}
self = url
}
}
@liamnichols
Copy link
Author

This is extremely useful since the regular URL.init(string:) method can (rightly so) return nil if the value passed does not represent a valid URL.

This is frustrating when you’re passing a hard coded string that you know for sure is valid since you’ll need to force unwrap it and on projects with stricter code style guidelines this might be disallowed.

As an alternative, this extension allows for a StaticString to be considered as safe by providing a non-failable initialiser instead.

StaticString is useful since it represents a string known at compile time which we treat as an understanding that the programmer has verified that the contents is valid whereas a regular String could have been constructed at runtime (such as API response data) where we have no way of verifying that the contents is valid.

example code showing a compiler warning

All credit to @Ecarrion for the idea 🎉

@Ecarrion
Copy link

Another safe(good?) practice is to have some kind of URLs repository type that is backed up by unit tests in case a wrong URL goes unnoticed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment