Created
July 10, 2020 06:52
-
-
Save liamnichols/99ff878ce7d752e467c7b02f804242ce to your computer and use it in GitHub Desktop.
A non-failable initialiser extension for URL that accepts StaticString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.