Hi,
I have an Array that I’d like to contain different types (in order to populate a tableView)… the problem I have is accessing the elements inside that Array. I quickly threw together a playground that creates two different types of objects, then adds them to an Array of AnyObjects. I’m using an enum as the common thread between them to help distinguish their types when it comes time to populate the tableView to help with other conditional code within the cellForIndexPath.
Any hints on how to access the data within the elements? For instance, the variable “kind” within each object? A simple collection[0]. brings up nothing. Do I have to attempt to cast these as one of my types, then access the data within?
What would be the best way to do this casting in the cellForIndexPath method? I plan on having about 20 different types when it’s all said and done.
I’ve also tried creating an empty protocol, and having them both conform to it to avoid casting, but I still couldn’t access the data within each element when using a ‘for in loop’.
Thanks!
var collection = [AnyObject]()
enum Kind {
case Car, Animal
}
class Car {
var kind: Kind
var model: String
var year: Double
var passengers: [String]
var seats: Int
init(kind: Kind, model: String, year: Double, passengers: [String], seats: Int) {
self.kind = kind
self.model = model
self.year = year
self.passengers = passengers
self.seats = seats
}
}
class Animal {
var kind: Kind
var legs: Int
var domesticated: Bool
init(kind: Kind, legs: Int, domesticated: Bool) {
self.kind = kind
self.legs = legs
self.domesticated = domesticated
}
}
let vw = Car(kind: .Car, model: "GTI", year: 2010, passengers: ["Mike", "Sarah", "Elise", "Henry"], seats: 4)
let coyote = Animal(kind: .Animal, legs: 4, domesticated: false)
let jeep = Car(kind: .Car, model: "Cherokee", year: 2014, passengers: ["Sarah", "Mike"], seats: 5)
collection.append(vw)
collection.append(coyote)
collection.append(jeep)
// the collection now contains [Car, Animal, Car], but I cannot access collection[0].kind unless I cast it as a Car.