logoalt Hacker News

scottmflast Tuesday at 10:26 PM4 repliesview on HN

Thanks. What could possibly cause an invalid URL in this example though?


Replies

fainpulyesterday at 10:16 AM

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.

show 1 reply
mrbombasticlast Tuesday at 11:12 PM

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.

show 1 reply
jshieryesterday at 2:27 AM

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.

lawgimenezlast Tuesday at 11:54 PM

In my experience, migrating to a new API endpoint while your stubborn users just refused to update your app for some reason.