Search code examples
swiftpropertiessuperclass

Change superclass property type on swift


In a super Class called TableViewCell I have a property

class TableViewCell {
    var model: AnyObject?
}

In a class called CountryTableViewCell I wrote this code

class CountryTableViewCell : TableViewCell {

    var model:[AnyObject]? {

        didSet {
            // do some stuff
        }
    }
}

and I got this error

property model with [AnyObject]? cannot override a property with type Anyobject?

Is it not possible to change the property model to an array?


Solution

  • No, you cannot use like that. Also AnyObject should be replaced by Any if using Swift 3.

    You can change your code as below:

    class TableViewCell {
        var model: Any?
    }
    
    class CountryTableViewCell : TableViewCell {
    
        override var model: Any? {
            didSet {
            }
        }
    }
    

    Now if you want to get an array of the model in didSet then you can type cast it as below code.

    class CountryTableViewCell : TableViewCell {
    
            override var model: Any? {
                didSet {
                   if let arrModel = model as? [Any] {
                      // Do Stuff...
                   }
                }
            }
    }