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.
For example, if you create a Person
struct with a name
property, then tried to write an initializer that accepted a name
parameter, self
helps you distinguish between the property and the parameter – self.name
refers to the property, whereas name
refers to the parameter.
Here’s that in code:
struct Person {
var name: String
init(name: String) {
print("\(name) was born!")
self.name = name
}
}
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.