Junior — Middle
Can you give an example when an object of a class is created on the stack instead of the heap?
sobes.tech AI
Answer from AI
In iOS, objects of classes are usually created on the heap, since classes are reference types. However, if you use structures (struct), which are value types, they are created on the stack.
Example:
struct Point {
var x: Int
var y: Int
}
func createPoint() {
let p = Point(x: 10, y: 20) // created on the stack
print(p)
}
Here, Point is a structure, and the variable p is created on the stack. For classes, for example:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
func createPerson() {
let person = Person(name: "John") // object on the heap, reference on the stack
print(person.name)
}
Thus, class objects are created on the heap, while structures are on the stack.