DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on

1

Day 9 : 100DaysOfSwiftšŸš€

Day 9
Structs Part 2

Initializers

Initializers are special methods that provide different ways to create your struct. All structs come with one by default, called their memberwise initializer

struct User {
    var username: String
}

var user = User(username: "Saurabh")

print(user.username) //Saurabh
Enter fullscreen mode Exit fullscreen mode

We can provide our own initializer to replace the default one. For example, we might want to create all new users as ā€œAnonymousā€ and print a message, like this:


struct User {
    var username: String

    init() {
        username = "Anonymous"
        print("Creating a new user!")
    }
}
Enter fullscreen mode Exit fullscreen mode

our initializer accepts no parameters, we need to create the struct like this:

var user = User()
user.username = "Saurabh"

print(user.username)
//Saurabh
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More