8

I come from a php background... so I was wondering if there was such a thing as var_dump for Xcode, I know about NSLog but I want it to act like var_dump.

Is there a function for this?

Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115

3 Answers3

9

In swift you can use dump(var) which uses mirror for introspection and useful for classes.

For example:

let pet = Pet(name:"Max", age: 4)
let adam = Person(name:"Adam", age: 30, pet:pet)

print("\(pet)")
print("\(adam)")
print("======")
dump(pet)
dump(adam)

The output will be:

Pet
Person
======
▿ Pet #0
  - name: "Max"
  - age: 4
▿ Person #0
  - name: "Adam"
  - age: 30
  ▿ pet: Optional(Pet)
    ▿ some: Pet #1
      - name: "Max"
      - age: 4
little
  • 2,927
  • 2
  • 25
  • 36
  • To use print() or dump() inside a view, you can assign it to a let e.g., `let _ = dump(pet)`. – TimD Feb 16 '23 at 14:38
2

In code:

NSLog(@"%@", myVar);

which is equivalent to

NSLog(@"%@", [myVar description]);

Or in the debugger: right click on the variable, and select "Print description".

If you want to inspect objects of your own classes this way, you need to implement the method -(NSString *)description for those classes.

TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
2

NSObject defines the description method, which provides a description of the object. The default implementation just prints the name of the class, but it's commonly overridden by subclasses to provide a more meaningful description of their content.

This is for instance the case of NSArray and NSDictionary, whose implementation produces a NSString representing the objects stored in the collection.

When you do

NSLog(@"%@", anObject);

description is automatically called on the object to retrieve a textual representation of it.

Also in the debugger you can do

po anObject

to achieve the same result.

Bottom line, if you need to provide a representation of a custom class you implemented, the way to go is to override description.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235