#11: Print object's content with dump

We already talked about debugging via print custom statements before.

What if instead of displaying some message you are more interested in seeing the content of an object?

The dump method is the right tool for the job, you don’t need to roll out your own implementation using the Mirror class.

Let’s define a complex object with a bit of structure to see what this method produces as output:



struct Inner{
    let anInt=0
    let aString="This is a string"
    let anotherString="This is a string too"
    let anArray = [0,1,2]
}

struct Outer{
    let i1 = Inner()
    let heyString = "Hey! It's me!"
    let i2 = Inner()
}


var a = Outer()
dump(a)

// Output:
//▿ Outer
//  ▿ i1: Inner
//    - anInt: 0
//    - aString: "This is a string"
//    - anotherString: "This is a string too"
//    ▿ anArray: 3 elements
//      - 0
//      - 1
//      - 2
//  - heyString: "Hey! It's me!"
//  ▿ i2: Inner
//    - anInt: 0
//    - aString: "This is a string"
//    - anotherString: "This is a string too"
//    ▿ anArray: 3 elements
//      - 0
//      - 1
//      - 2

The output can be configured with a few additional parameters:


    func dump<T>(_: T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

This short post is one of the Swift Bites, click the link for more!


This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.