Fix: Can’t Print Memory Address in Swift

Fix: Can't Print Memory Address in Swift

Written by

in

Quick answer: For a variable such as a Swift String, use withUnsafePointer(to:) and print the pointer inside its closure. For a class instance, use Unmanaged.passUnretained(instance).toOpaque(); the variable’s storage address and the object’s address are different things.

Why this happens

Swift distinguishes between a variable’s storage and a reference-type object. A String is a value type, so there is no class-instance address to print for the string itself. You can inspect a pointer to a variable holding the value, but that pointer is valid only within the scope provided by the API.

A class variable, by contrast, holds a reference to an instance. The address of that variable’s storage is not necessarily the address of the instance. Choose which one you need before printing it.

Older examples may recommend unsafeAddressOf, but current Swift code should use the APIs below instead.

How to fix it

1. Print a value variable’s address inside a pointer closure

Use withUnsafePointer(to:) to access the storage of a variable temporarily. Pass the variable with &, and print the pointer inside the closure:

var text = "A String"

print("Value: \(text)")
withUnsafePointer(to: &text) { pointer in
    print("Variable storage address: \(pointer)")
}

The pointer refers to storage containing the String value for the duration of the closure. Read or print the value before entering the closure, as shown, rather than accessing text separately while its storage is being accessed through the pointer.

Do not return or save the pointer for later use. Its validity is limited to the closure, and Swift does not promise that an address observed in one call will remain the same in another call. Compiler optimizations and temporary storage can affect what you observe.

This address also does not necessarily point to the string’s character bytes. A String can use different internal representations, so the address of the value’s storage is not a substitute for an API that provides access to its encoded contents.

2. Print a class instance’s address

For a reference type, use Unmanaged.passUnretained to obtain an unmanaged reference and toOpaque() to convert it to an opaque pointer:

final class Session {}

let session = Session()

withExtendedLifetime(session) {
    let address = Unmanaged.passUnretained(session).toOpaque()
    print("Instance address: \(address)")
}

This is the closer equivalent to printing an Objective-C object’s address with %p. passUnretained does not add ownership of the instance. The withExtendedLifetime block makes the intended lifetime explicit while the address is being printed.

Treat the result as a diagnostic value, not as a pointer you can safely dereference. Do not rely on it after the instance has been deallocated. An address can also be reused for another allocation later, so it is not a permanent identifier.

Unmanaged is for class instances, not Swift value types. Casting a String to AnyObject can bridge it to an Objective-C object, but the resulting address identifies that bridged object—not the storage address of the original Swift variable. Use the first method for the latter.

3. Use object identity when you only need a comparison

If the real question is whether two references point to the same instance, compare them with === instead of printing addresses:

final class Session {}

let first = Session()
let same = first
let second = Session()

print(first === same)   // true
print(first === second) // false

For an identity value that you can use in a set or dictionary, Swift also provides ObjectIdentifier:

let firstID = ObjectIdentifier(first)
let sameID = ObjectIdentifier(same)
let secondID = ObjectIdentifier(second)

print(firstID == sameID)   // true
print(firstID == secondID) // false

ObjectIdentifier describes the identity of a class instance during its lifetime. It is useful for in-process bookkeeping, but it should not be saved as a durable identifier for a later app launch or treated as a substitute for retaining the object.

4. Distinguish a reference variable from its instance

You can inspect both kinds of address when debugging a class reference:

final class Session {}

var reference = Session()

withUnsafePointer(to: &reference) { pointer in
    print("Reference variable storage: \(pointer)")
}

withExtendedLifetime(reference) {
    let address = Unmanaged.passUnretained(reference).toOpaque()
    print("Referenced instance: \(address)")
}

The first line printed inside a closure describes storage for the reference variable. The second describes the instance to which that reference points. They answer different questions, so do not expect them to match.

If you assign the same instance to another variable, the variables can have different storage locations while still referring to the same object. Use === to check that relationship without depending on the printed pointer values.

How to prevent it

  • Decide whether you need a value’s storage address, a class instance’s address, or just an identity comparison.
  • Keep pointers obtained from withUnsafePointer(to:) inside its closure.
  • Keep a class instance alive while using an unretained pointer for diagnostics.
  • Do not use addresses as persistent identifiers or assume they stay fixed across calls or launches.
  • Avoid bridging a value to AnyObject when you mean to inspect the original Swift variable.

FAQ

Can I print the address of a let value with withUnsafePointer?

The & form shown above requires a mutable variable, so declare it with var when you need to inspect its storage that way. The pointer is still temporary and must not escape the closure.

Why do two references to the same object have different variable addresses?

Each variable has its own storage for a reference. Both references can nevertheless point to the same class instance; use === to check.

Can I use a printed address as an object ID?

Only as a short-lived debugging clue. An address can be reused after deallocation, and it is not a stable identifier across app launches. For an in-process identity comparison, use === or ObjectIdentifier instead.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.