Init: A Special Note
A special init method is called when a class, struct, or enum is initialized. In Swift, you can define initialization parameters, just like with any other method:
| class Person { |
| |
| init(name: String) { |
| // your init implementation |
| } |
| |
| } |
| |
| Person(name: "Mr. Roboto") |
Notice that, unlike other methods, the first parameter name of an init method is required externally when the class is instantiated.
It is best practice in most cases to add a different external parameter name—fromName, in this case—to make the initialization more readable:
| class Person { |
| |
| init(fromName name: String) { |
| // your init implementation |
| } |
| |
| } |
| |
| Person(fromName: "Mr. Roboto") |
And of course, just like with other methods, you can ...
Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.