Initializers are special methods that provide different ways to create your struct. All structs come with one by default, called their memberwise initializer – this asks you to provide a value for each property when you create the struct.
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:
You don’t write func before initializers, but you do need to make sure all properties have a value before the initializer ends.
struct User {
var username: String
init() {
username = "Anonymous"
print("Creating a new user!")
}
}
var user = User()
user.username = "two straws"
output
Creating a new user!
Inside methods you get a special constant called self, which points to whatever instance of the struct is currently being used. This self value is particularly useful when you create initializers that have the same parameter names as your property.
struct Person {
var name: String
init(name: String) {
print("\(name) was born!")
self.name = name
}
}