swiftprotocolsswift-extensions

Why do we add protocol conformance with extensions?


If I have a class Christmas, and a protocol Merry, to make Christmas conform to Merry, many people would do it this way:

class Christmas {
    ...
}

extension Christmas: Merry {
    ...
} 

It's also encouraged by Apple.

However, isn't it more convenient to just make the class conform to protocol when it's defined? Like this:

class Christmas: Merry {
    ...
}

What's the difference between the 2 methods?


Solution

  • They are different coding styles. The first option

    class Christmas {
       ...
    }
    
    extension Christmas: Merry {
        ...
    }
    

    is cleaner when you're looking at the whole class. You can instantly see all the protocol implementations the class conforms to.

    Using the second option you put the implementation of the protocol inside the class mixing it with the class methods. However, if you use

    //MARK: - 
    

    the code becomes not less clean, than when you use extensions. For example:

    protocol Merry: class {
        func celebrate()
    }
    
    class Cristmas: NSObject, Merry {
        private var santa: AnyObject?
    
        //MARK: - Private Methods
        private func callSanta() {
            //calling Santa
        }
    
        //MARK: - Merry Implementation
        func celebrate() {
            //celebration starts here
        }
    }
    

    and when looking at the whole class you clearly see the separation of the protocol implementation: enter image description here

    The functionality of both options is the same.