Adding Elements to Optional Array turning up nil?

时间:2015-06-30 13:43:50

标签: swift

So here's what I got:

  • Owner Class
  • Pet Class
  • PetType Class

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?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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