“Value” type vs. “Reference” type?

Hi guys! I have just read an article on “Value types in Swift”. It seems a little confusing but interesting especially to such amateurs like me. I came up with a few experiments to understand it more comprehensively.

First of all, you can read the article here to get some conceptual ideas about value types and reference types (in Swift).

I think after reading the article, the big question on the top of your mind is

“What types in Swift are value types, reference types?”

Well, the blog pointed out some value types as follows:

  • Struct, Enum, Tuple
  • Primitive types: Int, Float, Bool, String, Array, Dictionary…

And reference types: Classes (Ex: NSObject)

[Q1]: “How about NSString, it is a subclass of NSObject,
then must be a reference type, right?”

Yeah, that’s right.

[ Q2]: “So, this leads to different results
when using value type vs. reference type?”

Good question! Hold on a second and carry out some experiments:

(1) Create 2 NSStrings
(2) Check if nsstring1 and nsstring2 hold the same reference

Of course yes, they are reference type which means the same memory address.

(3) Let’s mutate nsstring2. Can you guess the value of nsstring1?

Wait a minute! They are different. Besides, they don’t point to the same memory address anymore. It acts like a value type’s behaviours. Such a confusion! → [Confusion #1]

(4) Reassign nsstring2 to nsstring1

Now they point to the same memory address again.

Answer for [Q2]

Briefly, my answer is: “the same regarding the data/value results”.

Explanation for [Confusion #1]

I haven’t figured out what’s below the tip of the iceberg. But i guess it’s related to the protocols that NSString conforms to:

If you know the explanation, feel free to raise your voice. I would appreciate it. Thank you!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.