Luca
Luca

Reputation: 11016

use of extensions in Swift

I am looking at some sample code from some Apple Developer sample projects and I see this pattern repeating quite a few times.

So there is a view controller...

class CameraViewController: UIViewController {
}

and then there is always some extension to that as something like:

extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
   ...
}

I am wondering why it is done like this? Is this to allow reusability of the initial defined classes or is there some other reason?

Upvotes: 0

Views: 103

Answers (2)

resand91
resand91

Reputation: 69

Contributing to the answer, this is to better organize your projects, and not having such a ViewController:

extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate, ... {
    ...
}

Not only making use of Apple protocols but also organizing your methods into extensions.

For example, I organized my main ViewController with view creation methods to code, something like this:

extension MainViewController {
    private func createView() {
    ...
    }

   private func configureConstraints() {
    ...
    }
}

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299663

If it's in the same file, it's just for code organization purposes. It's convenient to keep methods together that relate to a specific protocol. It's a good reminder not to change the names of those methods, and it makes clear why a method might seem never to be called (since it's called from Apple code, for example).

If it's in another file, it's sometimes to simplify code-reuse, particularly if a very general-purpose type is conformed to a very app-specific protocol. But even in that case, it may just be for organizational purposes, to make files smaller, or just to express that you consider this to be non-core functionality.

But broadly, extensions are a very common and general-purpose tool that you can use whenever you find them convenient and meaningful.

Upvotes: 4

Related Questions