Day 9 : 100DaysOfSwiftšŸš€

100rabhcsmc

Saurabh Chavan

Posted on August 21, 2022

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
šŸ’– šŸ’Ŗ šŸ™… šŸš©
100rabhcsmc
Saurabh Chavan

Posted on August 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 9 : 100DaysOfSwiftšŸš€
swift Day 9 : 100DaysOfSwiftšŸš€

August 21, 2022