0
0
Swiftprogramming~10 mins

Why classes exist alongside structs in Swift - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a struct in Swift.

Swift
struct Person { [1] 
    var name: String
}
Drag options to blanks, or click blank then click option'
A(
B<
C[
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or square brackets instead of curly braces.
2fill in blank
medium

Complete the code to create an instance of a class in Swift.

Swift
let person = [1]()
Drag options to blanks, or click blank then click option'
APerson
Bstruct Person
Cclass Person
Dfunc Person
Attempts:
3 left
💡 Hint
Common Mistakes
Including 'class' or 'struct' keywords when creating an instance.
3fill in blank
hard

Fix the error in the code to correctly copy a struct instance.

Swift
var person1 = Person(name: "Alice")
var person2 = [1]
Drag options to blanks, or click blank then click option'
Aperson1()
B&person1
Cperson1
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Using & to reference the variable, which is not needed for structs.
4fill in blank
hard

Fill both blanks to show how classes behave differently from structs when assigned.

Swift
class PersonClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var personA = PersonClass(name: "Bob")
var personB = [1]
personB.name = "Charlie"
print(personA.name) // [2]
Drag options to blanks, or click blank then click option'
ApersonA
B"Bob"
C"Charlie"
DPersonClass(name: "Bob")
Attempts:
3 left
💡 Hint
Common Mistakes
Thinking classes copy values like structs do.
5fill in blank
hard

Fill all three blanks to complete the code that demonstrates why classes exist alongside structs.

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

class Circle {
    var center: [1]
    var radius: Int
    init(center: [2], radius: Int) {
        self.center = center
        self.radius = radius
    }
}

let centerPoint = Point(x: 0, y: 0)
let circle1 = Circle(center: centerPoint, radius: 5)
let circle2 = circle1
circle2.center.x = 10
print(circle1.center.x) // [3]
Drag options to blanks, or click blank then click option'
APoint
BCircle
C0
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Assuming changing circle2.center.x changes circle1.center.x because Circle is a class.