Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value type and reference type in Swift

Tags:

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

like image 721
Mayank Jain Avatar asked Oct 19 '25 04:10

Mayank Jain


1 Answers

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.

like image 106
Paulw11 Avatar answered Oct 21 '25 19:10

Paulw11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!