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

[Question on Day 58] Why using "let variable" can change properties

Forums > 100 Days of SwiftUI

On day 58: https://www.hackingwithswift.com/books/ios-swiftui/filtering-fetchrequest-using-nspredicate I dont know why below code works?

          let ship1 = Ship(context: moc)
          ship1.name = "Enterprise"
          ship1.universe = "Star Trek"

When you "let ship1", why you can still change the name and universe properties? I mean ... why not "var ship1"

Can someone explain for me?

1      

It's because Ship is a class, not a struct.

With classes, let means that you cannot change the instance that the variable points to—so you can't replace one Ship with another Ship—but you can change the properties of the instance that the variable points to.

let ship1 = Ship(context: moc)
ship1.name = "Enterprise"
ship1.universe = "Star Trek"

//this will not work
ship1 = Ship(context: moc)
ship1.name = "Millennium Falcon"
ship1.universe = "Star Wars"

//this will work
ship1.name = "Defiant"

4      

thanks! I got it ^_^

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.