Mayank Jain
Mayank Jain

Reputation: 5754

Value type and reference type in Swift

As per the apple documentation String is a Struct (value type) and NSString is Class (Reference type). Reference type means if we change the value of reference it will reflect in the original value too. check the below code.

Can anyone explain me what will be the output of below code and why?

import UIKit

var str:NSString = "Hello, playground"

var newStr = str

newStr = "hello"

print(str)
print(newStr)

According to me both str and newStr should print hello as they are reference type, but the output is

Hello, playground

hello

Upvotes: 4

Views: 934

Answers (2)

Rishab
Rishab

Reputation: 1957

Reference type means if we change the value of reference it will reflect in the original value too.

Yes, that is true. However in your code newStr = "hello" you are not changing the value of reference type. As Paulw11 pointed out in the comment newStr = "hello" assigns newStr as a reference to a different constant string.

Let's say that str is pointing to and address 0xAAAA.

var newStr = str causes newStr to point to 0xAAAA.

newStr = "hello" now points to another address of the constant string hello. Lets say the address is 0xBBBB

As you can see str is pointing to 0xAAAA and newStr is pointing to 0xBBBB, hence they are bound to produce different results.

Upvotes: 3

Paulw11
Paulw11

Reputation: 114875

First, NSString is immutable, so although it is a reference type, it cannot be changed.

Now, when you say var str:NSString = "Hello, playground" you are setting str as a reference to a constant string "Hello, playground".

You then have var newStr = str, so newStr and str will both refer to the same constant string.

Finally you have newStr = "hello", so newStr now refers to a different constant string. At no time did you modify the original constant string "Hello, playground", and indeed you can't since it is both a constant and an immutable class.

If, however, you use an NSMutableString and write:

var str:NSMutableString = NSMutableString(string:"Hello, playground")

var newStr = str

newStr.append(". Hello")

print(str)
print(newStr)

Then you will get the output

Hello, playground. Hello

Hello, playground. Hello

Since you are modifying the one object that is referenced by both variables.

Upvotes: 5

Related Questions