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