控制器中的重复代码

Duplicate codes in 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
    }
}

控制器 B

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

我目前的解决方案是有另一个 class C,并将重复的代码移入其中。但是,如果我这样做,控制器可以转换为 AVCaptureMetadataOutputObjectsDelegate,但不能转换为 UIViewController.

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

所以A和B会有

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

我的问题是是否可以将控制器转换为 UIViewController。或者还有其他方法可以正确重构代码吗?

如何扩展 AVCaptureMetadataOutputObjectsDelegate 协议并通过协议扩展(POP 方法)创建默认实现?

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 {
...
}

试试这个:

//declare your default method to be used across classes
protocol MyProtocol {
   func myFunc()
}

//provide the implementation of your default behavior here in myFunc()
extension MyProtocol {
    func myFunc() {
       print("Default behavior")
 }
}

class A: MyProtocol {

}

class B: MyProtocol {

}

let a = A()
a.myFunc()

let b = B()
b.myFunc()

//prints
Default behavior
Default behavior