NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Reply to this topic…

You need to create an account or log in to reply.

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.