2
2
.
.
4
4
.
.
5
5
E
E
x
x
t
t
e
e
n
n
s
s
i
i
o
o
n
n
s
s
I
I
n
n
f
f
o
o
Extensions are used to add Computed Properties and Methods to: Classes, Structures, Enumerations or Protocols.
E
E
x
x
t
t
e
e
n
n
s
s
i
i
o
o
n
n
S
S
y
y
n
n
t
t
a
a
x
x
Extension is declared by
using Keyword extension
followed by the Name of existing Data Type Person
followed by the Body which can have
Computed Properties var greet : String { get { return("Hello \(name)") } }
Methods func sayHello () { print("Hello world") }
Extension Syntax
//DECLARE STRUCT.
struct Person {
//DECLARE PROPERTIES.
var name : String
var age : Int
//DECLARE METHODS.
func display (name: String, age: Int) -> () {
print("\(name) is \(age) years old")
}
}
//DECLARE EXTENSION.
extension Person {
//ADD COMPUTED PROPERTIES.
var greet : String {
get { return("Hello \(name)") }
}
//DECLARE METHODS.
func sayHello () {
print("Hello world")
}
}
//REFERENCE EXTENSION COMPUTED PROPERTIES & METHODS.
var person : Person = Person(name: "John", age: 20)
person.sayHello()
print(person.greet)