lazy

Discussion in 'iOS Programming' started by grandM, Mar 5, 2017.

  1. grandM macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #1
    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!
     
  2. KALLT macrumors 601

    Joined:
    Sep 23, 2008
    #2
    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.
     

Share This Page