Junior
What data types can references be used with in Swift?
sobes.tech AI
Answer from AI
In Swift, references (by address) are used with:
- Classes: Instances of classes are reference types. When assigning a class instance to a variable or constant, a reference to the object is copied, not the object itself.
- Closures: Capturing variables in closures occurs by reference.
- Actors: Instances of actors are also reference types.
- Some system types: For example,
AnyObject,NSObject, and types from the Core Foundation set (e.g.,CFString). - Incoming/outgoing function parameters (
inout): Allow passing variables by reference so that the function can modify their values.
// Example with a class
class MyClass {
var value = 10
}
let instance1 = MyClass()
let instance2 = instance1 // instance2 references the same object
instance2.value = 20
print(instance1.value) // Will print 20
// Example with inout
func modifyValue(value: inout Int) {
value = value * 2
}
var myInt = 5
modifyValue(value: &myInt)
print(myInt) // Will print 10
Structures, enumerations, and tuples are value types, and when assigned or passed, their contents are copied, not referenced.