Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Rafael Robles
Rafael Robles
3,907 Points

Changing property value within struct

I can't seem to wrap my head around getters/setters in Swift. I have this simple code, and can't change the value of the property within the struct

struct Example{
   var x = 0

   func changeX(){
     x = 1
   }
}

I get an error saying cannot assign to 'x' in 'self'

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Rafael,

By default a struct is immutable meaning functions defined within them cannot modify the data within the struct, we can however get around this by prefixing the function with mutating; setting this allows us to then modify the existing data within the struct.

struct Example {
   var x = 0

   mutating func changeX() {
     x = 1
   }
}

One thing to note is you don't want the mutating keyword prefixed to all your functions, you would only use it for simple changes, anything other than that is recommended to be modified using the variable you assigned the instance to which provides 100% control over the struct.

http://stackoverflow.com/a/24035861