0
0
Swiftprogramming~5 mins

String is a value type behavior in Swift

Choose your learning style9 modes available
Introduction

Strings in Swift act like copies when assigned or passed around. This means changing one string does not change another.

When you want to keep original text safe while making changes to a copy.
When passing strings to functions and you want to avoid unexpected changes.
When storing strings in collections and you want each item independent.
When working with user input that should not affect other parts of the program.
Syntax
Swift
var original = "Hello"
var copy = original
copy += ", world!"

Strings are value types, so assigning one string to another copies the value.

Modifying the copy does not affect the original string.

Examples
The original string stays "Hi" while the copy changes to "Hi there!".
Swift
var greeting = "Hi"
var anotherGreeting = greeting
anotherGreeting += " there!"
print(greeting)
print(anotherGreeting)
The function gets a copy of the string, so the original "Hello" stays unchanged.
Swift
func changeString(_ text: String) -> String {
    var newText = text
    newText += "!"
    return newText
}

let message = "Hello"
let excitedMessage = changeString(message)
print(message)
print(excitedMessage)
Sample Program

This program shows that changing 'second' does not change 'first' because strings are value types.

Swift
var first = "Swift"
var second = first
second += " is fun"
print("first: \(first)")
print("second: \(second)")
OutputSuccess
Important Notes

Value types like String copy their data when assigned or passed, unlike reference types that share data.

This behavior helps avoid bugs from unexpected changes to shared data.

Summary

Strings in Swift behave as value types, copying data on assignment.

Changing a copied string does not affect the original.

This makes string handling safer and more predictable.