sffsf sffsf - 2 months ago 16
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.

Sample:

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

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

Answer

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

fruits.append(Apple())

or an Orange

fruits.append(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")
    }
}
Comments