In Swift, ‘Self’ represents the current Class, Struct, Enum and Protocol. While ‘self’ refers to the current instance itself.
Let’s take examples to get Difference between self and Self in Swift:
Self:
struct Car {
var color: UIColor
var wheels: Int
static func createObject() -> Self {
return Car(color: .white, wheels: 4)
}
}
let carObj = Car.createObject() //It will return the ‘Car’ object
The ‘Self’ point in the ‘Car’ class in the example above. Instead, we can use “Car” on Self as shown below.
struct Car {
var color: UIColor
var wheels: Int
static func createObject() -> Car {
return Car(color: .white, wheels: 4)
}
}
Above both example will work same.
We take another example:
extension Int {
static var one: Self {
Self(1.0)
// Here we are converting float number (1.0) to Int, Self refer to Int Struct
}
}
print(Int.one)
//Output - 1
Usage of Self in Protocols:
protocol InstanceCreator {
static func create() -> Self
//Self return an instance of the same type as the conforming type
}
class Car: InstanceCreator {
var carModel: String?
var color: UIColor?
init(carModel: String? = nil, color: UIColor? = nil) {
self.carModel = carModel
//This self point to current class instance
self.color = color
}
static func create() -> Self {
return Car(carModel: "BMW", color: .black) as! Self
}
}
Here, in ‘InstanceCreator’ protocol – we are using ‘Self’ that return the instance of the same type as the conforming type.
‘self’- This is a keyword in swift point to current instance of a class or struct within scope of that instance is methods or properties.
self:
class Car {
var carModel: String?
var color: UIColor?
init(carModel: String? = nil, color: UIColor? = nil) {
self.carModel = carModel
self.color = color
}
func displayCar() {
print("Car Model: \(carModel)")
}
}
In init method – carModel and colour are distinguished by ‘self’. ‘self’ point to the current class object. self.carModel means carModel object of car class.
Conclusion:
If we define difference between self and Self in Swift in simple definition:
“The current instance of a class or structure is denoted by “self” (lowercase “s”), whereas the type of the current instance is denoted by “Self” (capital “S”).”