I don't believe this feature can actually deliver on those promises, though. Firstly - what has been proposed by the Foundation team is that URLs specified as string literals will fail at runtime rather than return an optional. So when you write:
let url = URL(string: "http://example.com")!
// ^ ---- This
The force-unwrap is now implicit. That is it. No compile-time validation. You don't write the force-unwrap, but it's like an Array subscript in that it will trap at runtime and crash your app if it fails. The force unwrap is still there.
I mentioned this when the Foundation team posted their pitch - they are talking about this like it is compile-time validation, and people might be mistaken in to thinking that it is, but it isn't. It's a built-in force-unwrap and that can be a pretty significant difference.
Ergonomics of the recently-pitched Foundation.URL would benefit greatly from the ability to require the string argument to be compile-time constant. [...] While a type like
StaticString
may be used to require that the argument string must be static, which string is chosen can still be determined at runtime, e.g.:URL(Bool.random() ? "https://valid.url.com" : "invalid url . com")
EDIT: I misunderstood this. It is a (minor) expressivity feature.
But this part doesn't make a huge amount of sense:
With evolving compile-time evaluation facilities, Swift may even gain an ability to perform compile-time validation of such URLs even though the user may never be able to express a fully compile-time constant
Foundation.URL
type because this type is a part of an ABI-stable SDK.
On the one hand, we can validate URL values at compile time even though it's part of an ABI-stable SDK, but on the other hand, we can't create "fully compile-time constants" because it's part of an ABI-stable SDK?
So... what about if we validate the URL and say it is valid, but that turns out to be a bug? The OS updates, fixes the bug, now it says the URL is invalid -- but we already compiled the code and said it was valid! What are we going to do? Throw the App in to a crash loop? Let it continue with an invalid value?
That may be what happens now, but at least now we return an Optional
. We give the user the opportunity to handle errors (or trap, if they decide to), and we don't present any kind of illusion of compile-time validation.
This proposal makes very big promises, but I highly doubt it can deliver on them. It is extremely vague and presents concepts in a misleading way.