0
0
Swiftprogramming~20 mins

Structs are value types (copy on assign) in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Struct Mastery
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?

Consider this Swift code using a struct. What will be printed?

Swift
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 5, y: 10)
var p2 = p1
p2.x = 20
print(p1.x, p2.x)
A5 20
B20 20
C5 5
D20 5
Attempts:
2 left
💡 Hint

Remember that structs are value types and are copied when assigned.

Predict Output
intermediate
2:00remaining
What is the value of 'a.count' after this code runs?

Look at this Swift code. What is the value of a.count after execution?

Swift
struct Counter {
    var count: Int
}

var a = Counter(count: 1)
var b = a
b.count += 1
ACompilation error
B2
C0
D1
Attempts:
2 left
💡 Hint

Think about whether a and b share the same data or not.

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

Examine this Swift code. Why do the two print statements output different values?

Swift
struct Score {
    var points: Int
}

var s1 = Score(points: 10)
var s2 = s1
s2.points = 20
print(s1.points)
print(s2.points)
ABecause s2 was not properly assigned, it still references s1, so both print 10.
BBecause structs are value types, s1 and s2 are independent copies, so s1.points remains 10.
CBecause structs are reference types, s1 and s2 point to the same data, so both print 20.
DBecause the print statements are inside a closure capturing s1.points, both print 10.
Attempts:
2 left
💡 Hint

Recall how structs behave when assigned to new variables.

📝 Syntax
advanced
2:00remaining
Which option causes a compile-time error?

Given this struct, which code snippet will cause a compile-time error?

Swift
struct Person {
    var name: String
    var age: Int
}

let p1 = Person(name: "Alice", age: 30)
var p2 = p1
Ap1.name.append(" Smith")
Bp2 = Person(name: "Charlie", age: 25)
Cp2.age += 1
Dp2.name = "Bob"
Attempts:
2 left
💡 Hint

Consider mutability of struct instances and their properties.

🚀 Application
expert
3:00remaining
How many items are in the array after this code runs?

Consider this Swift code using structs and arrays. How many elements does arr2 contain after execution?

Swift
struct Item {
    var id: Int
}

var arr1 = [Item(id: 1), Item(id: 2)]
var arr2 = arr1
arr2.append(Item(id: 3))
A1
B2
C3
DCompilation error
Attempts:
2 left
💡 Hint

Think about how arrays and structs behave when assigned and modified.