Different between Self and self in Swift
In Swift programming language, "Self" and "self" have specific meanings and usage within the context of object-oriented programming.
- 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()
- 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.
Subscribe to my newsletter
Read articles from Abdulsamad Zuhair directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by