DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on

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)