Swift - Strings as Value Types

Introduction

In Swift, String is a value type.

When you assign a string to another variable, or pass a string into a function, a copy of the string is always created.

Consider the following code snippet:

var originalStr = "This is the original"
var copyStr = originalStr

In the preceding example, originalStr is initialized with a string literal and then assigned to copyStr.

A copy of the string literal is copied and assigned to copyStr.

If you output the values of both variables, you can see that both output the same string literal:

var originalStr = "This is the original"
var copyStr = originalStr

print(originalStr)  //This is the original
print(copyStr)      //This is the original

Now let's make a change to the copyStr variable by assigning it another string literal:


copyStr = "This is the copy!"

What happened here is that copyStr is now assigned another string.

To prove this, output the values of both variables:

Demo

var originalStr = "This is the original"
var copyStr = originalStr

copyStr = "This is the copy!"

print(originalStr)/*www .  ja v  a 2 s .  co  m*/
print(copyStr)

Result

Related Topic