Search code examples
iosswiftoverridingvar

Overriding variable property with different type


I have a variable 'children', which is just a list of participants. Can one please explain how can I override a variable with one type to a property with another type.

Here is a code:

class ParticipantsListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var participantsTableView: UITableView!

    // Error on next line: Property 'children' with type '[Child]?' cannot override a property with type '[UIViewController]'
    var children: [Child]?
    var trackingHelper = TrackingHelper()
    var modelHelper = ModelHelper.shared
}

Solution

  • The problem is very simple. You can't do that. UIViewController, the class you're inheriting from, has this property under lock and key. You'll need to create yourself a new solution depending on what you're trying to achieve:

    Condition A: Child is a subclass of UIViewController

    In this case, you want a way to make the child view controllers of ParticipantsListViewController always conform to Child. One way to do this would be the following computed property:

    var listChildren: [Child] {
        return children.filter { $0 is Child }
    }
    

    Condition B: Child is NOT a subclass of UIViewController

    You're trying to override something that the system needs to be there. Things in the children array have to be instances or subclasses of UIViewController. It's strict.

    Your solution here is easy. Name the property differently and get rid of the override. Sure, it won't have the nicest, simplest name children, but that's the way it goes.