Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the init! failable initializer?

The Apple Swift Programming Language guide mentions the existence of the init! initializer, but does not provide any example for it. (Search for init! in this page)

I understand the use of a normal failable initializer declared with init?, but I fail to get the need of this other version. What is it needed for? Can somebody provide an example?

like image 888
Matteo Manferdini Avatar asked Oct 20 '22 21:10

Matteo Manferdini


1 Answers

This serves two purposes:

  • When importing Cocoa APIs that Swift doesn't know about. If Swift does not know if an initializer can return nil or not, it annotates it with ! so that the developer knows there might be a nil hiding there, without forcing the dev to test for nil if there's actually no reason to.

  • For the same reasons implicitly-unwrapped optionals are used in other contexts (you may be willing to trade compile-time safety for added convenience in some cases).

like image 148
Thomas Deniau Avatar answered Oct 23 '22 06:10

Thomas Deniau