Meaning
● Self is alias for a Type like class Person
● self is alias for an Instance like var person = Person("John")
Usage
● Self can be used inside
○ Type in which case it is alias for that Type
○ Protocol in which it is alias for a Type that implements Protocol
● self can be used only inside
○ Type in which case it is alias for Instance
self inside Type
struct Person {
var name : String
func printName() {
print("\(self.name)")
}
}
var person = Person(name: "John")
person.printName() //John
Self inside Type: as reference to static member
struct Person {
static var name : String = "Unknown"
static func printName() {
print("\(Self.name)") //Alias for Type Person
print("\(Person.name)") //Unknown
}
}
Person.printName()
Self inside Protocol as: return value
protocol Person {
func getInstance () -> Self //Return instance of Type that implements Protocol
}
struct Employee : Person {
var name : String
func getInstance () -> Self {
return self
}
}
var employee = Employee(name: "John").getInstance()
print(employee.name)