DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Why You Might Need To Know Algorithms as a Mobile Developer: Emoji Example

Trending

  • How to Write for DZone Publications: Trend Reports and Refcards
  • From Fragmentation to Focus: A Data-First, Team-First Framework for Platform-Driven Organizations
  • Article Moderation: Your Questions, Answered
  • AI-Assisted Coding for iOS Development: How Tools like CursorAI Are Redefining the Developer Workflow
  1. DZone
  2. Coding
  3. Frameworks
  4. You say Constructor Chaining, Swift says Initializer Delegation

You say Constructor Chaining, Swift says Initializer Delegation

By 
Ricky Yim user avatar
Ricky Yim
·
Aug. 07, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
9.6K Views

Join the DZone community and get the full member experience.

Join For Free

One of the things that one must get used to with a new language is dealing with new conventions. Now coming from mostly a Java and Ruby background, there is a notion of constructors and constructor chaining, basically when one constructor calls another one. So when it comes to Swift, there are a few rules around the methods used to create objects.

Firstly, the language guide refers to constructors as initializers. So basically anytime you want to use the term constructor, use the term initializer when you are in Swift land. More specifically, constructor chaining is known as initializer delegation.

Initializers fall into two categories, Designated and Convenience.Designated initializers are the primary initializers and are responsible for initializing all properties of a class. So in this case, the only initializer here is known as the Designated one.

class Person {  
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

Now if you want to add other initializers to delegate to the Designated one, they will be known as Convenience initializers. So let's add one that defaults the age. Convenience initializers have the keyword conveniencebefore them.

class Person {  
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    convenience init(name: String) {
        self.init(name: name, age: 100)
    }
}

Convenience initializers need to delegate to another Convenienceinitializer or a Designated initializer.

Here's an example of a Convenience initializer calling another Convenienceone.

class Person {  
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    convenience init(name: String) {
        self.init(name: name, age: 30)
    }

    convenience init() {
        self.init(name: "Homer")
    }
}

If you wanted to, you could create another Designated initializer. Now we have two Designated initializers and two Convenience initializers.

class Person {  
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }

    convenience init(name: String) {
        self.init(name: name, age: 30)
    }

    convenience init() {
        self.init(name: "Homer")
    }
}

What about subclasses?

Once again, with initializers, there are certain rules that need to be adhered to when subclassing. So Designated initializers must call otherDesignated initializers in their immediate parent class.

So let's take a look at an example. We are adding a Student class as a subclass of the Person class. It will add a property student number.

class Student : Person {

    let number: String

    init(name: String, age: Int, number: String) {
        self.number = number
        super.init(name: name, age: age)
    }
}

Here we are calling the Designated initializer in the Person class. If we tried to call one of the Convenience initializers in the Person class, a compile error would occur. Also note, we need to assign the number property before calling the initializer in the parent class as it is a requirement to ensure all properties are initialized in child classes before their respective parent initializer is called.

Summary

Basically in summary, as explained in the language guide, Designatedinitializers delegate up and Convenience initializers delegate across. I hope this article helped in some way to improve your understanding of initializers in Swift.

References

  • Swift Language Guide
Swift (programming language) Delegation (object-oriented programming)

Published at DZone with permission of Ricky Yim, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Why You Might Need To Know Algorithms as a Mobile Developer: Emoji Example

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!