UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

day 10 classes (Mutability)

Forums > 100 Days of Swift

what is the difference between constant class & variable class ?

3      

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.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.