Complete the code to define a struct in Swift.
struct Person { [1]
var name: String
}The struct body must be enclosed in curly braces { }.
Complete the code to create an instance of a class in Swift.
let person = [1]()To create an instance, use the class name followed by parentheses.
Fix the error in the code to correctly copy a struct instance.
var person1 = Person(name: "Alice") var person2 = [1]
Assigning one struct instance to another copies the value.
Fill both blanks to show how classes behave differently from structs when assigned.
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]
Assigning a class instance copies the reference, so changing personB changes personA.
Fill all three blanks to complete the code that demonstrates why classes exist alongside structs.
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]The class Circle holds a struct Point. Changing circle2.center.x does not affect circle1.center.x because Point is a value type.
