Day 9 : 100DaysOfSwiftš
Saurabh Chavan
Posted on August 21, 2022
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
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!")
}
}
our initializer accepts no parameters, we need to create the struct like this:
var user = User()
user.username = "Saurabh"
print(user.username)
//Saurabh
š šŖ š
š©
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.