Search code examples
iosswiftswift2ios9

Duplicate codes in Controller


I am currently working on one project. It may potentially have duplicated codes in multiple controllers like below.


Controller A

class A: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    // about 50~70 lines of codes
    @IBAction func scanButtonTapped {
        // used self (as AVCaptureMetadataOutputObjectsDelegate)
        // used view
        // called presentViewController(...), which is a func in UIViewController
    }
}

Controller B

class B: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    @IBAction func scanButtonTapped {
        // will need same logic as in Controller A
    }
}

My current solution is have another class C, and move the duplicated codes into it. However, if I do so, controller can cast to AVCaptureMetadataOutputObjectsDelegate, but not to UIViewController.

class C {
    func btnTapped (view: UIView, controller: AnyClass) {
        // logic is here
        // controller can cast to AVCaptureMetadataOutputObjectsDelegate
        // but controller cannot cast to UIViewController
    }
}

so A and B will have

class A {
    @IBAction func scanButtonTapped {
        let c = C()
        c.btnTapped(view, self)
    }
}

My question is if it is possible to cast controller into UIViewController. OR is there another way to refactor the codes properly?


Solution

  • What about extend AVCaptureMetadataOutputObjectsDelegate protocol and create default implementation by protocol extension (POP approach)?

    protocol ScanButtonClickable: AVCaptureMetadataOutputObjectsDelegate {
        func btnTapped() // this line is optional
    }
    
    extension Clickable where Self: UIViewController {
        func btnTapped() {
            // logic is here
        }
    }
    
    class A: UIViewController, ButtonClickable {
    ...
    }
    
    class B: UIViewController, ButtonClickable {
    ...
    }