News for hackers. Stuff that matters.
Re:Apple’s Use of Swift in iOS 13 by untog on Thursday September 26, 2019 @05:01PM (#21085501)
A guard statement requires you to actually handle the error, though. The exclamation mark will crash the app.
Re:Apple’s Use of Swift in iOS 13 by saagarjha on Thursday September 26, 2019 @05:03PM (#21085528)
assertionFailure is not any more "handling the error" than a forcefully unwrapping the optional.
Re:Apple’s Use of Swift in iOS 13 by untog on Thursday September 26, 2019 @05:09PM (#21085572)
Yeah, it's also something you shouldn't do.
Re:Apple’s Use of Swift in iOS 13 by saagarjha on Thursday September 26, 2019 @05:14PM (#21085626)
What should you do when URL(string:) returns nil?
Re:Apple’s Use of Swift in iOS 13 by RandallBrown on Thursday September 26, 2019 @05:38PM (#21085834)
Obviously it depends heavily on what you're doing in your app and where that string is coming from.

Is it a hard coded string that will never change? Force unwrapping is probably appropriate.

Is it based on user input? Then you should probably tell the user the string they entered isn't a URL.

Re:Apple’s Use of Swift in iOS 13 by saagarjha on Friday September 27, 2019 @02:20AM (#21088995)
Right, and in that case it's pretty clear how errors can occur and what you should do to handle it.
Re:Apple’s Use of Swift in iOS 13 by swatcoder on Thursday September 26, 2019 @06:29PM (#21086281)
That's contextual. Maybe some combination of:

- abort and unwind the current action

- retry something

- log something

- abort the app explicitly

- fallback to a different value

- comment why this is a known-possible failure state

- present a message to the user

...

Re:Apple’s Use of Swift in iOS 13 by untog on Thursday September 26, 2019 @05:49PM (#21085944)
The one time you should unwrap it is if it's a constant - that way the app will always immediately crash if it's nil. Pretty difficult to not run into a bug like that.

But if you're creating it dynamically you should be guarding and throwing an error.