Classes Extensions when and why

Hi all,

I think a simple question, but not sure. In several of the videos I’ve see the authors add an extension method to a class. I use extensions a lot in C# so I understand the use. How ever, the only time I use them is when I want to extent a method on a class which I don’t have access to. e.g. from a framework or other external code source. Here I see people adding the extensions right after the class is defined.

If you wrote the class, why add extensions, as opposed to just putting the new method directly in the class?

Thanks,
Steve

It’s a nice way to keep your class organised. If I have a class inheriting from UIViewController I can have all the UIViewController methods in the main part of the class, and I expect to find them in that section. Then if I want to add a control that requires a delegate like a collection view, where my delegate will be that existing class, I like to make the delegate section an extension. Then you have something like

//MARK:- UICollectionViewDelegate
extension MyClass : UICollectionViewDelegate {
}

This also avoids a long list of protocols at the beginning of the class - you might be a delegate for a text field and a text view and a collection view and a picker view and be a data source too - it gets messy.

When you want to implement/review/edit the delegate methods you can find that MARK:- in the Xcode drop-down list in the module, and you can find all your delegate methods together rather than being mixed up throughout the view controller methods.

The other usage, adding features to a class you do not control is also common:

extension UIColor {
    class func cornflourBlue() -> UIColor {
        // create a colour matching HTML "CornflowerBlue" (#6495ED)
    }
}

Thanks for the reply. I understand it, but it will take some work to internalize it. I don’t use much in the way of delegates in my real job, so will have to read up on them.