无法覆盖Swift中的委托属性

时间:2015-07-30 17:29:52

标签: ios swift

我正在尝试制作与StudentPickerController类似的ImagePickerController

class StudentPickerController: UINavigationController, NSCoding {
    unowned(unsafe) var delegate: protocol<StudentPickerControllerDelegate, UINavigationControllerDelegate>?
}

@objc protocol StudentPickerControllerDelegate: NSObjectProtocol {
    optional func studentPickerControllerDidFinishPickingStudent(student: Student)
    optional func studentPickerControllerDidCancel()
}

然而,这给了我:

`Property 'delegate' with the type 'protocol<StudentPickerControllerDelegate, UINavigationControllerDelegate>?' cannot override a property with type 'UINavigationControllerDelegate?'`

查看UIImagePickerController的swift文件时,您可以看到:

class UIImagePickerController : UINavigationController, NSCoding {    
    unowned(unsafe) var delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>?
}

protocol UIImagePickerControllerDelegate : NSObjectProtocol {
    optional func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
    optional func imagePickerControllerDidCancel(picker: UIImagePickerController)
}

UIImagePickerController如何覆盖delegate,但我的班级不是?

我知道我可以简单地重命名我的属性以避免这种情况,但我想知道UIImagePickerController如何能够实现这一点。

2 个答案:

答案 0 :(得分:7)

  

所以我的问题是ImagePickerController如何能够覆盖委托,但我的类不是?

UIImagePickerController与Objective-C桥接,可以覆盖属性。所以如果你真的需要这个,那么你可能想在Objective-C中实现StudentPickerController并在Swift代码中使用它的桥接版本。

如果留在斯威夫特,你可以做的是:

class StudentPickerController: UINavigationController {
    private var studentDelegate: StudentPickerControllerDelegate?
    override var delegate: UINavigationControllerDelegate? {
        didSet { studentDelegate = delegate as? StudentPickerControllerDelegate }
    }
}

答案 1 :(得分:1)

您正在尝试为已有的类创建委托属性。您无法定义具有相同名称的新委托属性。

我相信您可以从StudentPickerControllerDelegate派生UINavigationControllerDelegate,然后将navigationController.delegate分配给符合StudentPickerControllerDelegate的对象。或者,您可以为代理使用不同的属性名称。