Updated for Xcode 13.3
Inside a method, Swift lets us refer to the current instance of a struct using self
, but broadly speaking you don’t want to unless you specifically need to distinguish what you mean.
By far the most common reason for using self
is inside an initializer, where you’re likely to want parameter names that match the property names of your type, like this:
struct Student {
var name: String
var bestFriend: String
init(name: String, bestFriend: String) {
print("Enrolling \(name) in class…")
self.name = name
self.bestFriend = bestFriend
}
}
You don’t have to use that, of course, but it gets a little clumsy adding some sort of prefix to the parameter names:
struct Student {
var name: String
var bestFriend: String
init(name studentName: String, bestFriend studentBestFriend: String) {
print("Enrolling \(studentName) in class…")
name = studentName
bestFriend = studentBestFriend
}
}
Outside of initializers, the main reason for using self
is because we’re in a closure and Swift requires it so we’re clear we understand what’s happening. This is only needed when accessing self
from inside a closure that belongs to a class, and Swift will refuse to build your code unless you add it.
SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.