October 2019
Intermediate to advanced
434 pages
11h 54m
English
The primary constructor is considered the default way to instantiate a class, but we can define secondary constructors as well to provide alternative ways to create a class instance. The following code shows how to add a secondary constructor to our School class:
class School { var name = "" constructor(schoolName: String) { name = schoolName }}
To add a secondary constructor, we can use the constructor keyword within the class body to define the new constructor logic. In this example, we've added a secondary constructor that takes a schoolName parameter to be assigned to the name property.
If a class has a primary constructor, then any secondary constructors must delegate to the primary constructor before any new ...
Read now
Unlock full access