Bright
Bright

Reputation: 5741

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?

Upvotes: 2

Views: 1568

Answers (3)

Anni S
Anni S

Reputation: 2026

There is difference between class conforms to protocol and the extension.

At the time of writing your class, you knew this should conforms to protocol then you can use class conforms to protocol. However, extensions are mean to extend functionality of existing classes. After writing your class and using it for a year, you need to add some additional feature to your class so instead of modify class, you can simply extend the class. Extension is not just for your classes, you can extend the behavior of every class available to you(native frameworks, third party libraries).

Upvotes: 1

Max Pevsner
Max Pevsner

Reputation: 4104

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.

Upvotes: 9

Sivajee Battina
Sivajee Battina

Reputation: 4174

There is a little difference. The first one confirms to protocol as you expected. Coming to second one that also confirms to protocol and in addition to that methods writing in extensions

extension Christmas: Merry {
    ...
} 

like this will make those methods available through out project with that Class name "Christmas"

Upvotes: 0

Related Questions