but in the other paragraph he said self point to the struct not instant
Which other paragraph are you referring to?
Below is the paragraph right after the one you quoted. It's the only other paragraph in that section. I don't see where he says self
points to the struct rather than the instance.
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.
Now, what you might be thinking of—and I'm not sure what day Paul gets around to talking about this—is the Self
that points to a type, like a struct or class.
Self
(with an uppercased s
) refers to a type.
self
(with a lowercased s
) refers to a particular instance of the type.
Example:
struct Thing {
let name: String
init(name: String) {
self.name = name //1
}
func copyWithReversedName() -> Self { //2
Thing(name: String(name.reversed()))
}
}
//1
: Here, self
"points to whatever instance of the struct is currently being used", just as in Paul's first paragraph you quoted.
//2
: Here, Self
"lets you conveniently refer to the current type without repeating or knowing that type’s name" (per the Swift language docs). It indicates that the function copyWithReversedName()
returns a Thing
struct without actually using the name "Thing". This would be convenient should you, for example, later rename this type to "Person"; you wouldn't have to go through the struct's code and change all the places you used Thing
because Self
would just refer to whatever the struct is.
Hope I didn't just confuse you even more. ;)