Tometoyou
Tometoyou

Reputation: 8376

How to simplify code

I have the following code:

class MySuperClass : UIViewController {
    var model: ModelA!
}

class ModelA {
    var aBool = true
}

class ModelB: ModelA {
    var boolBelongsToB = true
}

class MySubclass: MySuperclass {
    func testFunction() {
        let theBool = (model as! ModelB).boolBelongsToB // Simplify this
    }
}

var aSubclass = MySubclass()
var aModelB = ModelB()
aSubclass.model = aModelB

What I want to do is simplify having to use the code (model as! ModelB) everytime I want to access my model in MySubclass. How can I do this?

Upvotes: 0

Views: 63

Answers (1)

CodeR70
CodeR70

Reputation: 467

Why not just create a computed property in your subclass Y which returns the correct type. Like

var modelB: ModelB {get { return model as! ModelB }}

Instead of getting it then as "(model as! ModelB)" you can just get it as "modelB".

Upvotes: 2

Related Questions