O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required