Extensions are one of the interesting, Important && powerful features of the Swift && in Objective C these are termed as "categories".A extension allows us to add additional functionality to our class, structure, enumeration that is already existing. These comes a handy when we want new behaviour for a type but in particular context. Syntax of declaring extensions is same as we declare class, structures etc. Extensions are declared by "extension" keyword followed by name of the type that we want to extend && the extensions comes themselves. We c an add computed properties, methods, initializers etc as extensions. Here is an example of the extensions:
class Library {
var name: String = "Oxford"
var numberOfBooks = 200
func profile() -> String {
return "In \(self.name) library there are \(numberOfBooks) number of books."
}
}
Here goes the extension of this class:
extension Library {
var libraryState: String {
get {
return "United States \(self.name) library contains \(self.numberOfBooks) books."
}
}
}
Now create an object of Library class:
var lib = Library()
lib.name = "California"
lib.numberOfBooks = 2000
println(lib.libraryState)
As you can see that in the extension of the class we are using "self" which indicates the Library class itself and because it is an extension of the class Library so we are able to access the property of the class Library.The output of this code is printed on the console:
"United States California library contains 2000 books."