V
V
Vetter2019-08-08 13:39:03
iOS
Vetter, 2019-08-08 13:39:03

How to access the properties of child classes in an array consisting of elements of child classes without type casting?

There is a BaseBuilding base class and several child ones: Gallery, Tower, Shop
create an array
var arr = [BaseBuilding]()
and fill it with elements of child types.
if we do print(arr), we get:

[SomeName.Gallery, SomeName.Shop, SomeName.Tower, SomeName.Shop]

type(of: arr[2])produces the correct element type - Tower
But to access the properties of this element, you must first do a type cast.
let towerHeight = (arr[2] as! Tower).height
How to make it so that you can directly access the properties of child classes?
for the type construction to work.
let towerHeight = arr[2].height
I suspect that an extension is needed for array, but how exactly to extract the type of an array element?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
doublench21, 2019-08-08
@doublench21

It is forbidden! This is the essence of strongly typed languages.
type(of: )this type inference is dynamic, but the compiler is deep and with a bell tower before that. It only sees the type you originally specified. This is correct! There are no ifs, if you need some functionality from children within the parent, then create a protocol and describe them. These are the basics of OOP

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question