Hacker News new | ask | show | jobs
by scottmf 169 days ago
Thanks. What could possibly cause an invalid URL in this example though?
4 comments

Not OP, There is none as far as I can tell but still force unwrapping that way is something people try to avoid in Swift and often times have the linter warn about. Reason being people will copy the pattern elsewhere and make the assumption something is safe, ultimately be wrong and crash your app. It is admittedly an opinionated choice though.
there has been some talk ofmusing macros ro validate at runtime; personally i'd love it if that got in officially.

[0] https://forums.swift.org/t/url-macro/63772

Nothing. You would use `!` to force unwrap in this case.

I think the point of the comment was that in many cases, when constructing a url, you can't be sure that the input will result in a valid url (e.g. when receiving a string instead of an int), so you have to be more defensive and the required code is more verbose.

Anything taking arbitrary values or user input could cause an invalid URL, especially on earlier OS versions. Newer OS versions will use a newer URL standard which is more flexible. You could wrap your URL encoding logic into a throwing or non-throwing init as well, the example just used the simple version provided by Foundation.
In my experience, migrating to a new API endpoint while your stubborn users just refused to update your app for some reason.