Different between Self and self in Swift

Different between Self and self in Swift

Understanding the Distinction: Self vs. self in Swift Programming Language

In Swift programming language, "Self" and "self" have specific meanings and usage within the context of object-oriented programming.

  1. Self (capitalized): In Swift, "Self" with a capital "S" is used to refer to the current type within a class, struct, or enum. It is known as a "type-level" reference. It allows you to access static properties, call static methods, and refer to the type itself within the scope of the type definition. It is often used when you need to refer to the type explicitly, especially in cases where you have subclasses or when working with class methods.

Here's an example of using "Self" in Swift:

swiftCopy codeclass MyClass { class func myClassMethod() { print("This is a class method") } funcmyInstanceMethod() { Self.myClassMethod() } } let obj = MyClass() obj.myInstanceMethod() // Calls MyClass.myClassMethod()
  1. self (lowercase): In Swift, "self" with a lowercase "s" is used as an implicit parameter to refer to the current instance of a class or struct. It is typically used within the instance methods and closures of a class or struct to access properties, methods, or refer to the instance itself. It helps differentiate between instance variables and local variables or parameters with the same name.

Here's an example of using "self" in Swift:

swiftCopy codeclass MyClass { var value: Int = 0 func updateValue() { let closure = { [self] inself.value = 10 } closure() print(self.value) // Outputs 10 } } let obj = MyClass() obj.updateValue()

In the above example, "self" is used within the closure to capture and retain a reference to the instance of MyClass. It allows accessing and modifying the value property of the instance.

In summary, in Swift, "Self" (capitalized) refers to the current type within a class, struct, or enum, while "self" (lowercase) refers to the current instance of a class or struct and is commonly used within instance methods and closures.