Junior — Middle
In what ways is object passing implemented in a program?
sobes.tech AI
Answer from AI
In iOS, objects are usually passed in the following ways:
-
By reference: class objects are passed by reference, meaning a pointer to the object in memory is passed. Changes to the object in one part of the program are reflected everywhere there is a reference to this object.
-
By value: structures and enumerations in Swift are passed by value, meaning they are copied when passed.
-
Through delegates and closures: objects can be passed via delegates (protocols) or closures for callbacks and data transfer between components.
Example of passing an object by reference:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
func changeName(person: Person) {
person.name = "New Name"
}
let p = Person(name: "Ivan")
changeName(person: p)
print(p.name) // Will output "New Name"