2
2
.
.
4
4
.
.
8
8
S
S
e
e
l
l
f
f
v
v
s
s
s
s
e
e
l
l
f
f
I
I
n
n
f
f
o
o
[
[
R
R
]
]
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)
Self inside Protocol as: function parameter
protocol Person {
func getName (person: Self) //Accept instance of Type that implements Protocol
}
struct Employee : Person {
var name : String
func getName (person: Self) {
print(person.name)
}
}
var employee = Employee(name: "John")
employee.getName(person: employee)