In Swift, both classes and structs can store data and have methods. But classes have a feature that structs do not. What is the main reason to choose a class over a struct?
Think about how you can create a new type based on an existing one.
Classes support inheritance, which means you can create a new class based on an existing class, reusing and extending its behavior. Structs do not support inheritance.
Consider this Swift code:
struct PointStruct {
var x: Int
var y: Int
}
class PointClass {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
var a = PointStruct(x: 1, y: 1)
var b = a
b.x = 2
var c = PointClass(x: 1, y: 1)
var d = c
d.x = 2
print(a.x)
print(c.x)What will be printed?
Think about how structs and classes are copied or referenced.
Structs are value types, so when you assign 'a' to 'b', 'b' gets a copy. Changing 'b.x' does not affect 'a.x'. Classes are reference types, so 'c' and 'd' refer to the same object. Changing 'd.x' changes 'c.x'.
Look at this Swift code:
struct Person {
var name: String
mutating func changeName(newName: String) {
name = newName
}
}Why does this code cause a compile error?
Think about how structs handle methods that change their own data.
In Swift, methods that modify properties of a struct must be marked with the 'mutating' keyword. Without it, the compiler prevents modification inside the method.
Choose the correct Swift code that defines a class with a deinitializer that prints "Goodbye" when the object is destroyed.
Look for the special keyword Swift uses for cleanup code in classes.
Swift uses 'deinit' without parentheses to define a deinitializer. It runs when the class instance is about to be destroyed.
Consider this Swift code:
class Counter {
var count = 0
}
var c1 = Counter()
var c2 = c1
c2.count += 1
struct Wrapper {
var counter: Counter
}
var w1 = Wrapper(counter: Counter())
var w2 = w1
w2.counter.count += 1
print(c1.count)
print(w1.counter.count)What will be printed?
Remember how classes and structs behave when assigned and copied.
c1 and c2 refer to the same Counter instance, so incrementing c2.count changes c1.count to 1.
w1 and w2 are structs (value types), so w2 is a copy of w1. However, the 'counter' property is a reference to a class instance (reference type), so w1.counter and w2.counter refer to the same Counter object. Incrementing w2.counter.count changes w1.counter.count to 1.