【问题标题】:How to properly use 'self' in a protocol extension to avoid having to use protocol stubs?如何在协议扩展中正确使用“自我”以避免必须使用协议存根?
【发布时间】:2018-07-13 16:11:37
【问题描述】:

目前我们有一个协议和一个协议扩展:

protocol Camera: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

  func openTheCamera()
}

extension Camera where Self: UIImagePickerController {
    func openTheCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }
}

由于该函数已经在协议扩展中定义,我尝试直接在符合类中调用它:

class SomeClass: Camera {

 override func viewDidLoad() {
        super.viewDidLoad()
        openTheCamera()
    }
}

问题是当我尝试并符合该类时,我得到了错误:

类型 UIViewController 不符合协议“相机” 是否要添加协议存根?

问题是 func 已经在扩展中定义了,我不想再次将它添加到控制器中。如果我添加协议存根 (openTheCamera(){ }) 并在控制器中留空,那么我在协议扩展中定义的函数不会被执行。

【问题讨论】:

    标签: ios swift protocols swift-protocols


    【解决方案1】:

    协议条件错误。你应该使用:

    extension Camera where Self: UIViewController {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多