tory
tory

Reputation: 67

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
}

Upvotes: 0

Views: 993

Answers (3)

CodeBender
CodeBender

Reputation: 36640

You can accomplish this using protocol conformance for your Child view controllers as demonstrated here:

import UIKit

protocol ChildProtocol { }

class SomeViewController: UIViewController, ChildProtocol { }

class ParticipantsListViewController: UIViewController {
    override var children: [UIViewController] {
        return self.children.filter { viewController in viewController is ChildProtocol }
    }
}

So long as the view controllers that you wish to be a Child conform to ChildProtocol, then they will be returned via the children override.

Upvotes: 1

Robert Dresler
Robert Dresler

Reputation: 11200

No, you can't have children property with your custom type since property with the same name is already property of UIViewController (see docs) which is superclass of your view controller so your subclass has this property too.

So, you have to use other name for your variable.

Upvotes: 1

cookednick
cookednick

Reputation: 1088

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.

Upvotes: 1

Related Questions