Home > Mobile >  use of extensions in Swift
use of extensions in Swift

Time:05-02

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?

CodePudding user response:

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.

  • Related