Self Vs. self – What is the difference in Swift

Swift Programming

Difficulty: Beginner | Easy | Normal | Advanced

If you’ve embarked on your iOS development journey or recently found yourself in the midst of an iOS job interview, you’ve probably encountered the age-old question: What’s the difference between ‘Self’ and ‘self’?

This seemingly small distinction holds significant importance in Swift programming. Within this blog post, I will cover the key differences.

What are the key differences between Self and self in Swift?

  • Self' refers to the type of the current instance’s class or struct. This is often used in factory methods or initializer functions where you want to create and return an instance of the same type as the current class or struct. It helps ensure that you’re working with the correct type, especially in class hierarchies and when conforming to protocols with associated types.
  • self‘ refers to the current instance of a class, struct, or enum, commonly referred to as “the object.” It is used to access and manipulate instance properties, methods, and subscripts.

Explain like I’m 5 the difference between ‘Self’ and ‘self’ in Swift:

Imagine building cars out of Lego. Each car can have different sizes, colours or number of wheels (properties) . When you say ‘self’ you are referring to one of the Lego cars that you have built. This car can then be modified, made larger, or colour changes. ”Self’ on the other hand refers to all cars, even if the cars are look differently – ‘Self’ is referring to all cars despite them being built differently.

Demystifying Self vs. self in Swift

Self – type identity

Swift is known for its strong typing and its emphasis on safety. When it comes to defining and using types, ‘Self’ refers to the type.

  • Refers to the type itself within a class, struct, or enum.
  • Used for ensuring type integrity in Swift code.
  • Commonly employed in protocol conformance and class hierarchies.
  • Helps make code more robust when working with subclasses and protocols.
  • Ensures that the appropriate type is used.

self – current instance

While Self deals with types, ‘self’ is all about instances. It’s the keyword you use to access properties, methods, and subscripts of the current instance within a class, struct, or enum.

  • Refers to the current instance of a class, struct, or enum.
  • Used to access instance properties, methods, and subscripts.
  • Helps avoid naming conflicts with local variables or parameters.
  • Primarily focuses on working with instances, not types.
  • Ensures that you’re manipulating the current instance’s properties and methods.

Summary: what is Self Vs self Swift?

In Swift, ‘Self’ refers to the type of the current instance, while ‘self’ refers to the current instance itself.

Thank you for reading

If you enjoyed this article feel free to share it 👍, alternatively you can catch me on my socials: