3

On apple website, https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html it states that we can change a variable property in a structure. I am trying to change the person's last name. However I recieve an error at that line of code. Thank you for helping me.

import UIKit


struct people {
    let firstName : String
    var lastName : String
}

let person = people(firstName: "InitialFirstName", lastName: "InitialLastName")
person.lastName = "ChangedLastName" //<-- error

println(person.firstName)
println(person.lastName)

Error:

Playground execution failed: TestPlayground2.playground:12:17: error: cannot assign to 'lastName' in 'person' person.lastName = "ChangedLastName" ~~~~~~~~~~~~~~~ ^

Entitize
  • 4,553
  • 3
  • 20
  • 28

3 Answers3

10

You can only modify a property of a struct if that struct is declared as var, and not let. Even though your property is var, because the struct is let it is immutable.

var person = people(firstName: "InitialFirstName", lastName: "InitialLastName")
person.lastName = "ChangedLastName" //No problem!

Note that this is different behavior from classes. A class's mutable properties can be changed even if if the instance of the class is a constant.

Tone416
  • 540
  • 3
  • 10
5

Unlike class which is reference type struct is value type.
You have to declare the instance as mutable

var person = people(firstName: "InitialFirstName", lastName: "InitialLastName")
vadian
  • 274,689
  • 30
  • 353
  • 361
0

By using the 'let' syntax you have declared 'person' as a constant, which means that it's properties can't be changed. Just change 'let' to 'var' and the error will disappear.

Here's more info about the difference between let and var in swift.

Peter
  • 29
  • 1
  • 5