Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,564
327
Hi guys

Does anyone of you know how I could make the assignment of the currentAnimal. If I leave out the = animals.first it works perfectly. Then I'm assigning in viewDidLoad().

I just wondered if it could be done during the instantiation?

Code:
lazy var animals = Factory.generateAnimalArray(withNumberOfAnimals: 1000)
var currentAnimal: Animal? = animals.first

Thanks once more!
 
currentAnimal is an instance property. Instance properties need to have a value when the object is initialised. Either by setting a default value or by setting a value in init(). A lazy property will be set sometime after initialisation (that is the whole point, you don’t want it to have a value until you need it).

The solution depends on what you are trying to achieve. If you need currentAnimal to have a value before viewDidLoad() is called, then you need to make animals an instance property too. Alternatively, you can make it a static property if it can be same for all objects.
 
  • Like
Reactions: grandM
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.