To Fail or to Throw?
Initializing using a throwing initializer and try?
looks an awful lot like initializing with a failable initializer. So which should you use?
Consider using throwing initializers. Failable initializers can only express a binary failure/success situation. By using throwing initializers you can not only indicate failure, but also indicate a reason by throwing specific errors. Another benefit is that calling code can propagate any errors thrown by an initializer.
Failable initializers are much simpler though, since you don’t need to define an error type and you can avoid all those extra try?
keywords.
Why does Swift even have failable initializers? Because the first version of Swift did not include throwing functions, so the language needed a way to manage initialization failures.
Progress is what gets us to Mars, so we can grow rocks.
Progress is what gets us to Mars, so we can grow rocks.
Where To Go From Here?
Wow — you’re not only halfway through getting humans to Mars, you’re now a Swift structure initialization guru! You can download the final playground for Part 1 here.
To learn all about Swift class initialization, carry on to part 2 of this tutorial.
You can find more information about initialization in the initialization chapter of Apple’s The Swift Programming Language guide. If you have any questions or comments, please join the discussion in the forum below!