sffsf sffsf - 1 year ago 82
Swift Question

Swift. Collection of inherited objects

I have class Fruit as base class. I created 2 other classes which inherited from Fruit: Apple and Orange.

I need to add Apples and Oranges in array. I want to have Fruit class of that array. Is it possible?

And if so, how can I read items from that array and define class of it.


var ar: [Fruit] = [Apple, Apple, Orange]

for i in ar {
if i is Apple {
} else if i is Orange {

Answer Source

Given this

class Fruit { }
class Apple: Fruit { }
class Orange: Fruit { }

You can create an array if Fruit(s)

var fruits: [Fruit] = []

You can add an Apple


or an Orange


Iterating the fruits

for fruit in fruits {
    switch fruit {
    case let apple as Apple: print(apple)
    case let orange as Orange: print(orange)
    default: print("Another fruit")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download