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
Top comments (0)