How do I work with variables in Swift that have the type of a main class but are passed an instance of a subclass?
Here is a piece of example code:
class MainClass {
var name: String
init(name: String) {
self.name = name
}
}
class Num1: MainClass {
var num: Int = 1
}
class Num2: MainClass {
var num: Int = 2
}
struct ExampleView: View {
var subClassInstance: MainClass
var body: some View {
Text(subClassInstance.name)
Text(subClassInstance.num) // trying to access this property
}
}
let example = ExampleView(subClassInstance: Num1(name: "test"))
Specifically, I want to be able to access subclass properties from a variable with the type of a main class. In the context of my example, I want to be able to access the "num" property of the passed subclass instance from the variable in the view with type of MainClass. Is this possible? The motivation for doing this is having one view that works with similar subclasses of a main class--not having to write two views, one with a variable set to the type of each subclass.