如何在协议扩展中正确使用 'self' 以避免必须使用协议存根?
How to properly use 'self' in a protocol extension to avoid having to use protocol stubs?
目前我们有一个协议和一个协议扩展:
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:
的情况下直接调用它
class SomeClass: Camera {
override func viewDidLoad() {
super.viewDidLoad()
openTheCamera()
}
}
问题是当我尝试符合 class 时出现错误:
Typ UIViewController does not conform to protocol 'Camera'
Do you want to add protocol stubs?
问题是 func 已经在扩展中定义了,我不想再将它添加到控制器中。如果我添加协议存根 (openTheCamera(){ }) 并在控制器中留空,那么我在协议扩展中定义的函数不会被执行。
协议条件错误。你应该使用:
extension Camera where Self: UIViewController {
目前我们有一个协议和一个协议扩展:
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:
的情况下直接调用它class SomeClass: Camera {
override func viewDidLoad() {
super.viewDidLoad()
openTheCamera()
}
}
问题是当我尝试符合 class 时出现错误:
Typ UIViewController does not conform to protocol 'Camera' Do you want to add protocol stubs?
问题是 func 已经在扩展中定义了,我不想再将它添加到控制器中。如果我添加协议存根 (openTheCamera(){ }) 并在控制器中留空,那么我在协议扩展中定义的函数不会被执行。
协议条件错误。你应该使用:
extension Camera where Self: UIViewController {