Structs are value types and classes are reference types.
I'm just getting into Swift. I was reading a book Teach Yourself Swift in 24 Hours by BJ Miller at the local bookstore, and I came across the concept of structs, a special keyword in Swift that you can use in place of the class keyword. I had never heard of this before, so it was interesting to see this new programming weapon that's available in Swift. Here's the difference between the two:
BJ Miller expands on this idea and makes it very clear as he says, "Being a value type, a struct is passed by value, meaning that any time you need to send a struct to a function, or even create another variable or constant of an existing struct, a complete copy is made of the struct and the new copy is used in the new variable or constant". Of course, is actionscript 3 or java you save instance of the class to a variable in a Model class. Then that same instance can be accessed from other classes. But when you create a new struct and assign it to a new variable, they are two independent instances. He draws a great diagram that inspired me to draw a similar one in Google docs. This really helped it sink in for me:
Here's how you could make a struct and a class in Swift:
Your comment will be posted after it is approved.
Leave a Reply.
The posts on this site are written and maintained by Jim Lynch. About Jim...