July 2017
Intermediate to advanced
284 pages
6h 45m
English
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 ...
Read now
Unlock full access