Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or square brackets instead of curly braces.
✗ Incorrect
The struct body must be enclosed in curly braces { }.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Including 'class' or 'struct' keywords when creating an instance.
✗ Incorrect
To create an instance, use the class name followed by parentheses.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using & to reference the variable, which is not needed for structs.
✗ Incorrect
Assigning one struct instance to another copies the value.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Thinking classes copy values like structs do.
✗ Incorrect
Assigning a class instance copies the reference, so changing personB changes personA.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Assuming changing circle2.center.x changes circle1.center.x because Circle is a class.
✗ Incorrect
The class Circle holds a struct Point. Changing circle2.center.x does not affect circle1.center.x because Point is a value type.