Justin Rose
Justin Rose

Reputation: 1041

Adding Elements to Optional Array turning up nil?

So here's what I got:

Owner Class

This class simply declares a variable pet of type Pet?

class Owner {
  var pet: Pet?
}

Pet Class

This class simply declares an empty array of PetType

class Pet {
  var pets = [PetType]()
}

PetType Class

Two stored variables: petType(e.g. Dog), and petName(e.g. Harris) and a basic init method that takes two parameters: petType and petName

class PetType {
  var petType: String
  var petName: String

  init(petType: String, petName: String) {
    self.petType = petType
    self.petName = petName
  }
}

Note: This was all done in a Playground

let owner = Owner() // returns {nil}
var firstPet = PetType(petType: "Dog", petName: "Harris") // returns {petType "Dog" petName "Harris"}
owner.pet?.pets.append(firstPet) // returns nil
owner.pet?.pets[0].petName // returns nil

What am I doing wrong here?

Upvotes: 3

Views: 1815

Answers (2)

Shailesh Chandavar
Shailesh Chandavar

Reputation: 1614

As pet inside the owner class is optional until and unless you assign a pet object or create a pet object using init you will get nil.Optional value is forced unwrapped with ! (it means you are damn sure that value will be present in an optional),You can use optional binding if you are not sure about the value of optional. So the solution is:

 let owner = Owner()
 owner.pet = Pet()

 var firstPet = PetType(petType: "Dog", petName: "Harris")
 owner.pet!.pets.append(firstPet)
 owner.pet!.pets[0].petName

Upvotes: 2

Antonio
Antonio

Reputation: 72760

Owner has a property which is never initialized. By doing it inline:

class Owner {
    var pet: Pet? = Pet()
}

your code works as expected.

If you do not want to initialize it inline, then you have to modify the code using Owner accordingly:

let owner = Owner()
var firstPet = PetType(petType: "Dog", petName: "Harris")

owner.pet = Pet() // <-- here you have to initialize the `pet` property
owner.pet?.pets.append(firstPet)
owner.pet?.pets[0].petName

Upvotes: 3

Related Questions