self, Self, and Self.self in Swift
Let's dive into the fascinating world of self
, Self
, and Self.self
in Swift.
These seemingly similar constructs have distinct meanings and use cases.
What is self
(lowercase)?
When you're inside an instance method or property of a class, self
refers to the current instance of that class.
It's like saying, "Hey, I'm talking about myself!"
class Pokemon {
var name: String
init(name: String) {
self.name = name
}
func introduce() {
print("Hello, my name is \(self.name).")
}
}
let dragonite = Pokemon(name: "Dragonite")
dragonite.introduce() // Prints: "Hello, my name is Dragonite."
What is Self
(capital 'S')?
When you're working with protocols and protocol extensions, Self
(with a capital 'S') refers to the type that conforms to the protocol.
It's like saying, "Whoever adopts this protocol, listen up!"
protocol Duplicatable {
func duplicate() -> Self
}
In the Duplicatable protocol, Self is used to specify that the duplicate() method should return an instance of the conforming type.
The exact type is not specified in the protocol itself, but will be determined by the type that conforms to the protocol.
It allows each conforming type to have a clear contract: if you conform to Duplicatable, you must implement a duplicate() method that returns an instance of your own type.
What is Self.self
?
When you use Self.self
, you're referring to the type itself (not an instance).
It's like saying, "I want to talk about the blueprint, not the actual house."
class Animal {
static func describe() {
print("This is an animal.")
}
}
class Dog: Animal {
override class func describe() {
print("This is a dog.")
}
}
let someAnimalType = Animal.self
someAnimalType.describe() // Prints: "This is an animal."
let someDogType = Dog.self
someDogType.describe() // Prints: "This is a dog."
Practical Use Cases
-
self
:- Use it within instance methods to refer to properties or methods of the current instance.
- Helpful for avoiding naming conflicts between method parameters and instance properties.
-
Self
:- Great for defining default implementations in protocol extensions.
- Ensures that conforming types use the same implementation.
-
Self.self
:- Rarely used directly but can be handy when working with metatypes (e.g., creating instances dynamically).
Wrapping Up
self
is for instances.Self
is for protocols and protocol extensions.Self.self
is for talking about types themselves.
Conclusion
Understanding the differences between self
, Self
, and Self.self
is crucial for writing clean and maintainable Swift code.
Resources:
- https://docs.swift.org/swift-book/documentation/the-swift-programming-language/methods/
- https://nilcoalescing.com/blog/UseCasesForSelfInSwift
Read more
- Enhancing SwiftUI with CachedAsyncImage • 3 minutes reading time.
- SimpleNetworking • 5 minutes reading time.
- Understanding Package.swift • 13 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook