Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,650 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