Let's say you develop a class for your pets.
class Pet {
var name: String = "Waldo" // just sample initial value
var type: String = "Hampster" // sample initial value
}
Then you create a variable named myPet
. You can also initialize a shelterAnimal.
var myPet = Pet(name: "Gromit ", type: "Dog") // create an object
var shelterAnimal = Pet(name: "OneEyedPete", "Tabby Cat")
Because myPet
is a variable (var) you can change your pet to another pet, if you wish.
myPet = shelterAnimal // myPet is a variable, so it can change.
BUT, if you had created myPet as a let....
let myPet = Pet(name: "Gromit", type: "Dog") // constant
// this next line will fail.
myPet = shelterAnimal // FAIL. you cannot change the object!
Interestingly, while in the second example myPet
is a constant (because of let), you can still change your pet's name. Think of it this way... the body of your pet is the same (it's a constant). But you're able to change your pet's name. Gromit becomes Wendolene.
Paste this into Playgrounds...
class Pet {
var name: String = "Waldo"
var type: String = "Hampster"
// simple class initializer
init (newName: String, newType: String) {
name = newName
type = newType
}
}
var myPet = Pet(newName: "Gromit", newType: "Dog")
var shelterAnimal = Pet(newName: "One Eyed Pete", newType: "Tabby Cat")
myPet.name // verify the name
myPet = shelterAnimal // you now have a new pet! (sorry Gromit!)
myPet.name // verify the name.
let yourPet = Pet(newName: "Gromit", newType: "Dog") // You have a new pet! (you know who...)
yourPet.name = "Wendolene" // and your new pet gets a new name.
// yourPet = shelterAnimal // Uncomment this line. XCode objects!
yourPet.name // verify the name changed.