} else if item is Maths {
++mathsCount
}
}
println("Subjects in chemistry contains \(chemCount) topics and maths contains
\(mathsCount) topics")
When we run the above program using playground, we get the following result:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Subjects in chemistry contains 2 topics and maths contains 3 topics
Downcasting
Downcasting the subclass type can be done with two operators (as? and as!).'as?' returns
an optional value when the value returns nil. It is used to check successful downcast.
'as!' returns force unwrapping as discussed in the optional chaining when the downcasting
returns nil value. It is used to trigger runtime error in case of downcast failure
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}