'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?
Solution 1:[1]
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.
Solution 2:[2]
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() {
...
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rob Napier |
| Solution 2 | resand91 |
