Junior — Middle
Can you list the different types of reference types in Swift?
sobes.tech AI
Answer from AI
In Swift, reference types are types whose objects are passed by reference rather than by value. The main types of reference types in Swift:
- Classes (class) — the primary reference type. Class objects are created on the heap, and variables store references to them.
- Functions (closures) — closures in Swift are also reference types because they can capture and store references to external variables.
Unlike classes, structures (struct) and enumerations (enum) are value types.
Example of a class:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
let person1 = Person(name: "Ivan")
let person2 = person1
person2.name = "Peter"
print(person1.name) // Will output "Peter" because person1 and person2 refer to the same object