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 Intermediate Swift 2 Value Semantics, Type Methods and Inheritance Reference Semantics

Cody Adkins
Cody Adkins
7,260 Points

Value Types Vs. Reference Types

How do you tell the difference of a value type and a reference type when reading code?

3 Answers

For starters, structs, enums and tuples are value types, classes are reference types.

Here's a link to an article that goes into a bit more detail: https://developer.apple.com/swift/blog/?id=10

And here's another: https://www.raywenderlich.com/112027/reference-value-types-in-swift-part-1

Harish Yerra
Harish Yerra
10,031 Points

To better explain value type vs reference type let's take a physical representation:

Let's say we have a folder with many pieces of paper in it, and I want to share this folder with others. I can either make a copy of this folder and hand it out to everyone else or I can just share the same folder.

This is pretty much what value and reference type is.

A value type gives everyone a copy of the folder on initialization. So structs, which are a value type will have a copy of the folder. However, class which are a reference type will be working on the exact same folder so all changes made to that folder will be accessible to everyone. However, in structs if I change something then that change is only accessible to that one particular folder and not all folders.

I hope this helps!

Jakob Hansen
Jakob Hansen
13,746 Points

in the video he says Gabe says " But we can change the underlying object, thirdRobot as much as we want." Can someone explain to me what underlying means in this context, because I would think the underlying object would be Robot being the most basic ( superclass) object?

Thanks

Jakob Hansen He means that we can change the values of the different variable properties (here "model") of the class's ("Robot") instance ("thirdRobot") as much we want, even said instance is a let constant.