DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

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."
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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."
Enter fullscreen mode Exit fullscreen mode

Practical Use Cases

  • self :

  • Self :

  • Self.self :

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:

Top comments (0)