0
0
Swiftprogramming~20 mins

String is a value type behavior in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift String Value Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code with strings?

Consider this Swift code where a string is assigned and then modified. What will be printed?

Swift
var greeting = "Hello"
var copy = greeting
greeting += ", world!"
print(copy)
ACompilation error
B"Hello, world!"
C"Hello"
D"world!"
Attempts:
2 left
💡 Hint

Remember that strings in Swift are value types, so copying creates a new independent value.

Predict Output
intermediate
2:00remaining
What happens when you modify a copied string?

What will this Swift code print?

Swift
let original = "Swift"
var copy = original
copy.append(" Lang")
print(original)
A"Lang"
B"Swift Lang"
CRuntime error
D"Swift"
Attempts:
2 left
💡 Hint

Think about whether modifying copy changes original.

🔧 Debug
advanced
2:30remaining
Why does this code print two different strings?

Examine this Swift code. Why does it print two different strings?

Swift
var s1 = "Hi"
var s2 = s1
s2 = "Hello"
print(s1)
print(s2)
ABecause strings are value types, s1 and s2 are independent copies.
BBecause strings are reference types, s1 and s2 point to the same data.
CBecause s2 was not assigned properly, it defaults to s1.
DBecause print statements are delayed and show old values.
Attempts:
2 left
💡 Hint

Think about how value types behave when assigned and changed.

🧠 Conceptual
advanced
1:30remaining
Which statement about Swift strings is true?

Choose the correct statement about Swift strings and value type behavior.

AModifying a copied string changes the original string.
BAssigning a string to a new variable creates a separate copy.
CStrings are reference types and share the same memory by default.
DStrings cannot be copied or assigned to new variables.
Attempts:
2 left
💡 Hint

Recall how value types behave on assignment.

Predict Output
expert
2:30remaining
What is the output of this Swift code with string mutation and copying?

Analyze this Swift code and determine what it prints.

Swift
var a = "Start"
var b = a
b += " End"
print(a)
print(b)
A"Start"\n"Start End"
B"Start End"\n"Start End"
CCompilation error
D"Start"\n"Start"
Attempts:
2 left
💡 Hint

Remember that strings are copied on assignment and changes to one do not affect the other.