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

[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?

2      

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"

5      

thanks! I got it ^_^

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.