BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

day 10 classes (Mutability)

Forums > 100 Days of Swift

what is the difference between constant class & variable class ?

1      

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.

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.