Search code examples
swiftswift-extensions

Why we use Extension?


As we have Object Oriented Programming, so we can make parent class which have all the functions those are needed for all child classes. so what is the purpose of extensions? I'm little bit confused in that question, please anyone help me.


Solution

  • Extensions

    Adds functions to your class without subclassing, is very useful in cases where you don´t have the implementation of the class you are trying to extend, example classes that are inside an Framework or library

    as is defined in https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

    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 are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

    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 In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions.

    NOTE

    Extensions can add new functionality to a type, but they cannot override existing functionality.

    Extension Syntax

    Declare extensions with the extension keyword:

    extension SomeType {
    // new functionality to add to SomeType goes here 
    }
    

    An extension can extend an existing type to make it adopt one or more protocols. To add protocol conformance, you write the protocol names the same way as you write them for a class or structure:

    extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here 
    }
    

    Adding protocol conformance in this way is described in Adding Protocol Conformance with an Extension.

    An extension can be used to extend an existing generic type, as described in Extending a Generic Type. You can also extend a generic type to conditionally add functionality, as described in Extensions with a Generic Where Clause.

    Hope this help to clarify you