Answer the question
In order to leave comments, you need to log in
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 let towerHeight = (arr[2] as! Tower).height
let towerHeight = arr[2].height
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question