Kyle Decot
Kyle Decot

Reputation: 20815

Unable to override delegate property in Swift

I'm attempting to make a StudentPickerController similar to ImagePickerController:

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

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

This however gives me:

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

When looking at the swift file for UIImagePickerController you can see:

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)
}

How is UIImagePickerController able to override delegate but my class is not?

I understand that I could simply rename my property to avoid this but I would like to know how UIImagePickerController is able to accomplish this.

Upvotes: 3

Views: 2949

Answers (2)

0x416e746f6e
0x416e746f6e

Reputation: 10136

So my question is how is ImagePickerController able to override delegate but my class is not?

UIImagePickerController is bridged from Objective-C, where it is possible to override properties. So if you really-really need this then you might want to implement StudentPickerController in Objective-C and use it's bridged version in Swift code.

If stay in Swift, what you can do is something like:

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

Upvotes: 9

Dan Loughney
Dan Loughney

Reputation: 4677

You are trying to create a delegate property for a class that already has one. You can't define a new delegate property with the same name.

I believe you can derive your StudentPickerControllerDelegate from UINavigationControllerDelegate and then assign the navigationController.delegate to your object that conforms to StudentPickerControllerDelegate. Or you can use a different property name for your delegate.

Upvotes: 1

Related Questions