Sobes.tech
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:

  1. 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.
  2. Closures: Capturing variables in closures occurs by reference.
  3. Actors: Instances of actors are also reference types.
  4. Some system types: For example, AnyObject, NSObject, and types from the Core Foundation set (e.g., CFString).
  5. 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.