Boon
Boon

Reputation: 41480

How to get the reference of a value type in Swift?

Value types such as struct and enum are copied by value. Is it possible to get the reference of variable of value types?

struct Test {}

let t = Test()
let s = t  // How to get a reference to t instead of a copy of t?

Upvotes: 2

Views: 1416

Answers (2)

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

The typical solution is to use a Box<T> reference type to wrap the value type. For example:

final class Box<T> {
    let value: T

    init(_ value: T) {
        self.value = value
    }
}

let t = Test()
let boxed = Box(t)
let anotherReference = boxed
let theValue = anotherReference.value

See https://www.natashatherobot.com/swift-generics-box/ for more info.

Upvotes: 3

Rob Napier
Rob Napier

Reputation: 299355

There are several ways to get a reference. Kristopher's Box solution is one of the most flexible, and can be built as a custom box to handle problems like passing structs to ObjC.

Beyond that, the most obvious is passing inout parameters. This isn't precisely the same thing as a reference, but its behavior can be very similar, and definitely can be a part of high-performance code.

And moving down the stack there is UnsafePointer and its friends, using withUnsafePointer(to:) on general types, or .withUnsafeBufferPointer on array types.

But if you need a persistent reference type that can be stored in a property, you'll need a Box as Kristopher describes.

(Just to capture it for future readers since I hadn't remembered it, but MartinR pointed it out in a comment: as AnyObject can automatically box value types.)

Upvotes: 4

Related Questions