Search code examples
swiftswift-macroswift5.9

Advantage of Swift macro for URL instead of runtime validation?


Reading about the new Swift macros in Swift 5.9 here and here, it seems like creating a macro to assess URL validity at compile time is a common example.

What are the advantages of checking URL validity at compile time rather than runtime? Considering that, by design, with the Swift language we are used to check it at runtime. I assumed it was because the URLs are dynamic and can go from valid to invalid and vice versa anytime.

Instantiating a URL with URL("https://www.google.com")! will work and I assume it could be checked at compile-time, but what if a less common URL becomes invalid later at runtime?

Thanks!


Solution

  • It seems you're misunderstanding what URL validation is doing in Swift.

    The URL(string:) initialiser checks whether the structure of the string provided is a valid URL - meaning that it doesn't contain any invalid characters (such as whitespaces, etc which need to be escaped in a URL).

    The initialiser doesn't check whether the URL actually points to an existing address. That's not even possible to do without firing off a network request to that URL and even then, whether the request succeeds or not isn't a definitive signal of whether the address is valid - you might be having connection issues on either the client or server side.

    So compile time checks for hardcoded URLs are completely safe, since once you instantiate a URL, you cannot change its underlying address.

    The proposed macros in the linked articles simply check whether the URL(string:) initialiser succeeds with the specified URL string - they don't do any extra validation either.