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 hidden or 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 | |
| } | |
| } |
Author
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
This is extremely useful since the regular
URL.init(string:)method can (rightly so) returnnilif the value passed does not represent a validURL.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
StaticStringto be considered as safe by providing a non-failable initialiser instead.StaticStringis 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 regularStringcould have been constructed at runtime (such as API response data) where we have no way of verifying that the contents is valid.All credit to @Ecarrion for the idea 🎉