Extensions are used to add Computed Properties and Methods to: Classes, Structures, Enumerations or Protocols.
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)