Brief Introduction About Swift
Swift is a language developed by Apple which is made using modern approach, include safety features and software design patterns. As the name suggests swift is fast, safe and easy to use. It is basically made a replacement for c-based family(C, C++ and Objective-C). It can be used to make apps and can be also used for cloud services and it is among the fastest growing languages.
Extensions in Swift
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling)”
Extensions in Swift can:
Add computed instance properties and computed type properties
Define instance methods and type methods
Provide new initializers
Define subscripts
Define and use new nested types
Make an existing type conform to a protocol
Syntax for Extension
extension someType {
// functionality to add goes here
}
Coding Example on Extensions
Let's say i want some inbuilt function for integers to increment and decrement by one. Let's make one
extension Int {
func incrementByOne() -> Int {
return (self + 1)
}
func decrementByOne() -> Int {
return (self - 1)
}
}
let number : Int = 2
print(number.incrementByOne()) //3
print(number.decrementByOne()) //1
Here self
refers to the value on which operation is done.
One more example to show you how you can use extensions in protocols
protocol Human {
func walking()
func sleeping()
}
class Men : Human {
func walking() {
print("Men is walking")
}
func sleeping() {
print("Men is sleeping")
}
}
extension Human {
func eating(person : String) -> String {
return ("\(person) is eating")
}
}
let objMen = Men()
print(objMen.eating(person : "Men")) //Men is eating
Here as we can see that we didn't provide eating method in protocol but is still available for class conforming to that protocol.
Hope, it helps and if you would like to add to it. Comment Below.
Top comments (0)