Honey Honey - 11 days ago 8
Swift Question

What exactly does debugger print when you are printing a dictionary?

I have a dictionary of type

[String : NSTimer]
.
When I use a breakpoint to print it in the console, I get the following results:

▿ 2 elements // Does this means 2 key-value pairs?
▿ [0] : 2 elements // What does this 2 element mean here?
- .0 : "https://github.jack.com" // what does .0 mean here?
▿ [1] : 2 elements
- .0 : "https://github.john.com"


However if I use the Variables view from Xcode I can see the value of the object as :

[0] (key: String, value: NSTimer)
key String "https://github.jack.com"
value NSTimer 0x00006100001726c0
[1] (key: String, value: NSTimer)
key String "https://github.john.com"
value NSTimer 0x00006000001756c0


Is this a bug? Or this is the intended behavior when printing a dictionary? If so why is that way?

Also is the [0], [1] just for the sake of differentiating between the keys? Because dictionaries have no order. right?

PS I have also wrote some questions inside my code

PDK PDK
Answer

First off, looks like you're not using the latest (stable) Xcode, because my Xcode (Version 8.1, 8B62) says:

Swift Compiler Error: 'NSTimer' has been renamed to 'Timer'

This hideous example does show "normal" output though:

let timerA = Timer(timeInterval: 123, repeats: false, block: { _ in })
let timerB = Timer(timeInterval: 123, repeats: false, block: { _ in })
let soExample: [String:Timer] = ["a":timerA, "b":timerB]
print(soExample)
dump(soExample)

Shows in the Console:

// ["b": <__NSCFTimer: 0x6000001738c0>, "a": <__NSCFTimer: 0x600000173440>]
// ▿ 2 key/value pairs
//   ▿ (2 elements)
//     - .0: "b"
//     - .1: <__NSCFTimer: 0x600000169180> #0
//       - super: NSTimer
//         - super: NSObject
//   ▿ (2 elements)
//     - .0: "a"
//     - .1: <__NSCFTimer: 0x600000169240> #1
//       - super: NSTimer
//         - super: NSObject

About the debug print:

Yes, you should see "2 key-value pairs".

Then a tuple of 2 elements: (key, value) …where .0 is shorthand for the first tuple element. (see The Swift Programming Language: Tuples)

Indeed, dictionaries have no ordering.

Dictionaries are unordered collections of key-value associations.

…so I agree with you that in the Variables view in Xcode, with its [0] and [1], can confuse newcomers—as you can see, the print outs in the Console don't confuse. ;-)

Comments