Is there a way to pretty print Swift dictionaries to the console?
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
prints out the following on the console:
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
prints out the following on the console:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?
ios swift xcode
add a comment |
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
prints out the following on the console:
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
prints out the following on the console:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?
ios swift xcode
4
You could usedump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…
– Moritz
Aug 4 '16 at 17:39
12
print(dictionary as! NSDictionary)
cheap trick?
– BaseZen
Aug 4 '16 at 17:41
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
1
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52
add a comment |
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
prints out the following on the console:
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
prints out the following on the console:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?
ios swift xcode
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
prints out the following on the console:
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
prints out the following on the console:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?
ios swift xcode
ios swift xcode
edited Aug 4 '16 at 17:39
Toland Hon
asked Aug 4 '16 at 17:37
Toland HonToland Hon
3,04712233
3,04712233
4
You could usedump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…
– Moritz
Aug 4 '16 at 17:39
12
print(dictionary as! NSDictionary)
cheap trick?
– BaseZen
Aug 4 '16 at 17:41
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
1
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52
add a comment |
4
You could usedump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…
– Moritz
Aug 4 '16 at 17:39
12
print(dictionary as! NSDictionary)
cheap trick?
– BaseZen
Aug 4 '16 at 17:41
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
1
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52
4
4
You could use
dump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…– Moritz
Aug 4 '16 at 17:39
You could use
dump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…– Moritz
Aug 4 '16 at 17:39
12
12
print(dictionary as! NSDictionary)
cheap trick?– BaseZen
Aug 4 '16 at 17:41
print(dictionary as! NSDictionary)
cheap trick?– BaseZen
Aug 4 '16 at 17:41
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
1
1
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52
add a comment |
11 Answers
11
active
oldest
votes
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
Usage:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
Output:
dump
prints the contents of an object via reflection (mirroring).
Detailed view of an array:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
Prints:
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
For a dictionary:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
Prints:
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
is declared as dump(_:name:indent:maxDepth:maxItems:)
.
The first parameter has no label.
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
Prints:
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
@JamesWolfeThis is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.
– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
add a comment |
SWIFT 3
Casting a dictionary to 'AnyObject' was the simplest solution for me:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: (dictionary as AnyObject)")
This is easier to read for me than the dump option, but note it won't give you the total number of key-values.
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
add a comment |
po solution
For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
add a comment |
Just another way using Functional Programming
dictionary.forEach { print("($0): ($1)") }
Output
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
This works for OP's[String: String]
dictionary, but it's not great for[AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.
– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
add a comment |
For debug purpose only I convert the Array or Dictionary to a pretty printed json:
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: (parseError)")
return "{}"
}
}
}
Then:
print("nHTTP request: (URL)nParams: (params.json())n")
Result on console:
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
add a comment |
I wouldn't consider a lot of the answers provided here true pretty printed JSON, as when you pass the results into a JSON validator the result is invalid (often due to the code including '=' rather than ':').
The easiest way I've found of doing this is just converting the JSON object to data using the pretty printed writing option then printing a string using the resulting data.
Here is an example:
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
Result:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
EDIT: It's been pointed out that the OP did not ask for JSON, however I find that the answers that recommend just printing or dumping the data into the console provide very little formatting (if any) and are therefore not pretty printing.
I believe that despite the OP not asking for JSON, it is a viable answer as it is a much more readable format for data than the horrendous format that is spat out into the console by xcode/swift.
1
Thanks, With this I was able to pretty print amid debugging viae let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
add a comment |
You can just use a for loop and print each iteration
for (key,value) in dictionary {
print("(key) = (value)")
}
Application in extension:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("(key) = (value)")
}
return self.description
}
}
Alternate application:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("(key) = (value)")
}
}
}
Usage:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
Output (Tested in Xcode 8 beta 2 Playground):
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
Since there's adescription
anddebugDescription
already, it might be more appropriate to call the varprettyDescription
and return the formatted string.
– Toland Hon
Aug 4 '16 at 18:43
add a comment |
For Swift 3 (& building on the brilliant answer by @Jalakoo), make the following Dictionary
extension:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
then print a dictionary of any hierarchy in a pretty way (better than dump()
) using this:
print(dictionary!.prettyPrint)
add a comment |
The methodology of converting the Swift Dictionary to json and back is the neatest. I usually use Facebook's chisel which has a pjson command to print a Swift dictionary.
Eg:
(lldb) pjson dict as NSDictionary
This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested.
P.S.
For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.
add a comment |
How about:
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("(key) = (value)n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
add a comment |
extension String {
var conslePrintString: String {
guard let data = """
.appending(
replacingOccurrences(of: "\u", with: "\U")
.replacingOccurrences(of: """, with: "\"")
)
.appending(""")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: ,
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\r\n", with: "n")
}
}
let code in extension String and it works fine
let string = "(jsonDictionary)".conslePrintString
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38773979%2fis-there-a-way-to-pretty-print-swift-dictionaries-to-the-console%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
Usage:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
Output:
dump
prints the contents of an object via reflection (mirroring).
Detailed view of an array:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
Prints:
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
For a dictionary:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
Prints:
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
is declared as dump(_:name:indent:maxDepth:maxItems:)
.
The first parameter has no label.
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
Prints:
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
@JamesWolfeThis is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.
– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
add a comment |
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
Usage:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
Output:
dump
prints the contents of an object via reflection (mirroring).
Detailed view of an array:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
Prints:
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
For a dictionary:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
Prints:
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
is declared as dump(_:name:indent:maxDepth:maxItems:)
.
The first parameter has no label.
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
Prints:
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
@JamesWolfeThis is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.
– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
add a comment |
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
Usage:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
Output:
dump
prints the contents of an object via reflection (mirroring).
Detailed view of an array:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
Prints:
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
For a dictionary:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
Prints:
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
is declared as dump(_:name:indent:maxDepth:maxItems:)
.
The first parameter has no label.
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
Prints:
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
Usage:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
Output:
dump
prints the contents of an object via reflection (mirroring).
Detailed view of an array:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
Prints:
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
For a dictionary:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
Prints:
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
is declared as dump(_:name:indent:maxDepth:maxItems:)
.
The first parameter has no label.
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
Prints:
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
edited Aug 4 '17 at 20:43
answered Aug 4 '16 at 18:47
MoritzMoritz
57.6k19131184
57.6k19131184
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
@JamesWolfeThis is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.
– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
add a comment |
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
@JamesWolfeThis is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.
– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
1
1
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
This is not pretty printed JSON, this is just dumping a a variable into the console - not valid JSON. While it does suit OP's needs I believe the question needs rewording to match this.
– James Wolfe
May 16 '18 at 13:54
1
1
@JamesWolfe
This is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.– Moritz
May 16 '18 at 15:34
@JamesWolfe
This is not pretty printed JSON
Nobody said it was. The OP asked about pretty printing Swift dictionaries - nobody is talking about JSON, except a few off-topic answerers. The OP's quesiton is not about JSON at all.– Moritz
May 16 '18 at 15:34
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
@JamesWolfe Also please do not change the question. That would be vandalism. The question is clear as it is, and it's not about JSON. Do not change a question just because some answers talk about something else. Thanks.
– Moritz
May 16 '18 at 15:43
add a comment |
SWIFT 3
Casting a dictionary to 'AnyObject' was the simplest solution for me:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: (dictionary as AnyObject)")
This is easier to read for me than the dump option, but note it won't give you the total number of key-values.
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
add a comment |
SWIFT 3
Casting a dictionary to 'AnyObject' was the simplest solution for me:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: (dictionary as AnyObject)")
This is easier to read for me than the dump option, but note it won't give you the total number of key-values.
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
add a comment |
SWIFT 3
Casting a dictionary to 'AnyObject' was the simplest solution for me:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: (dictionary as AnyObject)")
This is easier to read for me than the dump option, but note it won't give you the total number of key-values.
SWIFT 3
Casting a dictionary to 'AnyObject' was the simplest solution for me:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: (dictionary as AnyObject)")
This is easier to read for me than the dump option, but note it won't give you the total number of key-values.
edited Nov 21 '18 at 15:07
answered Jun 14 '17 at 16:23
JalakooJalakoo
1,76811417
1,76811417
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
add a comment |
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
2
2
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
Cool, but I can't understand why it's working.
– kelin
Dec 13 '17 at 8:26
2
2
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
It is a brilliant way and way better than dump
– AbdelHady
Feb 1 '18 at 18:04
add a comment |
po solution
For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
add a comment |
po solution
For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
add a comment |
po solution
For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
po solution
For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
edited Nov 13 '18 at 12:55
answered Oct 12 '17 at 18:39
Irshad MohamedIrshad Mohamed
694814
694814
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
add a comment |
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
1
1
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
Since is an expression and not an object, it should be 'p' and not 'po'. But thanks very much for this solution! Works fine for me
– Alessandro Francucci
Jul 6 '18 at 10:41
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
@AlessandroFrancucci does it matter? The command seems to do the same thing either way.
– nickjwallin
Nov 9 '18 at 20:02
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
Now both way of doing it are working. But before doing a "po print" didn't work for me. (po means print object.... which is a bit confusing if you have a print afterwards and not an object imho)
– Alessandro Francucci
Nov 12 '18 at 10:08
add a comment |
Just another way using Functional Programming
dictionary.forEach { print("($0): ($1)") }
Output
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
This works for OP's[String: String]
dictionary, but it's not great for[AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.
– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
add a comment |
Just another way using Functional Programming
dictionary.forEach { print("($0): ($1)") }
Output
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
This works for OP's[String: String]
dictionary, but it's not great for[AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.
– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
add a comment |
Just another way using Functional Programming
dictionary.forEach { print("($0): ($1)") }
Output
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
Just another way using Functional Programming
dictionary.forEach { print("($0): ($1)") }
Output
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
answered Aug 4 '16 at 17:50
Luca AngelettiLuca Angeletti
40.4k570116
40.4k570116
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
This works for OP's[String: String]
dictionary, but it's not great for[AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.
– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
add a comment |
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
This works for OP's[String: String]
dictionary, but it's not great for[AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.
– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
1
1
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
This should be the top answer. Works perfectly!
– Yuri Doubov
May 25 '17 at 20:37
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
Or to be "even more functional"... dictionary.map { "($0): ($1)" }.forEach(print) (tongue-in-cheek comment)
– Jon Willis
Nov 14 '17 at 1:01
2
2
This works for OP's
[String: String]
dictionary, but it's not great for [AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.– Christopher Pickslay
Feb 14 '18 at 23:03
This works for OP's
[String: String]
dictionary, but it's not great for [AnyHashable: Any]
dictionaries, where if a value is a dictionary, you're back to Swift's non-pretty printing.– Christopher Pickslay
Feb 14 '18 at 23:03
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
I have book marked this answer🙂, because I still cannot remember this syntax 🙄
– Nitin Alabur
Jul 23 '18 at 8:05
add a comment |
For debug purpose only I convert the Array or Dictionary to a pretty printed json:
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: (parseError)")
return "{}"
}
}
}
Then:
print("nHTTP request: (URL)nParams: (params.json())n")
Result on console:
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
add a comment |
For debug purpose only I convert the Array or Dictionary to a pretty printed json:
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: (parseError)")
return "{}"
}
}
}
Then:
print("nHTTP request: (URL)nParams: (params.json())n")
Result on console:
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
add a comment |
For debug purpose only I convert the Array or Dictionary to a pretty printed json:
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: (parseError)")
return "{}"
}
}
}
Then:
print("nHTTP request: (URL)nParams: (params.json())n")
Result on console:
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
For debug purpose only I convert the Array or Dictionary to a pretty printed json:
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: (parseError)")
return "{}"
}
}
}
Then:
print("nHTTP request: (URL)nParams: (params.json())n")
Result on console:
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
edited Sep 29 '17 at 14:35
answered Apr 14 '17 at 11:46
Marco MMarco M
827612
827612
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
add a comment |
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
what is bLog here ?
– Nitesh
Sep 28 '17 at 18:51
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
@Nitesh bLog is a simple custom logger with backtrace that I wrote, edited with print().
– Marco M
Sep 29 '17 at 14:34
add a comment |
I wouldn't consider a lot of the answers provided here true pretty printed JSON, as when you pass the results into a JSON validator the result is invalid (often due to the code including '=' rather than ':').
The easiest way I've found of doing this is just converting the JSON object to data using the pretty printed writing option then printing a string using the resulting data.
Here is an example:
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
Result:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
EDIT: It's been pointed out that the OP did not ask for JSON, however I find that the answers that recommend just printing or dumping the data into the console provide very little formatting (if any) and are therefore not pretty printing.
I believe that despite the OP not asking for JSON, it is a viable answer as it is a much more readable format for data than the horrendous format that is spat out into the console by xcode/swift.
1
Thanks, With this I was able to pretty print amid debugging viae let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
add a comment |
I wouldn't consider a lot of the answers provided here true pretty printed JSON, as when you pass the results into a JSON validator the result is invalid (often due to the code including '=' rather than ':').
The easiest way I've found of doing this is just converting the JSON object to data using the pretty printed writing option then printing a string using the resulting data.
Here is an example:
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
Result:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
EDIT: It's been pointed out that the OP did not ask for JSON, however I find that the answers that recommend just printing or dumping the data into the console provide very little formatting (if any) and are therefore not pretty printing.
I believe that despite the OP not asking for JSON, it is a viable answer as it is a much more readable format for data than the horrendous format that is spat out into the console by xcode/swift.
1
Thanks, With this I was able to pretty print amid debugging viae let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
add a comment |
I wouldn't consider a lot of the answers provided here true pretty printed JSON, as when you pass the results into a JSON validator the result is invalid (often due to the code including '=' rather than ':').
The easiest way I've found of doing this is just converting the JSON object to data using the pretty printed writing option then printing a string using the resulting data.
Here is an example:
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
Result:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
EDIT: It's been pointed out that the OP did not ask for JSON, however I find that the answers that recommend just printing or dumping the data into the console provide very little formatting (if any) and are therefore not pretty printing.
I believe that despite the OP not asking for JSON, it is a viable answer as it is a much more readable format for data than the horrendous format that is spat out into the console by xcode/swift.
I wouldn't consider a lot of the answers provided here true pretty printed JSON, as when you pass the results into a JSON validator the result is invalid (often due to the code including '=' rather than ':').
The easiest way I've found of doing this is just converting the JSON object to data using the pretty printed writing option then printing a string using the resulting data.
Here is an example:
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
Result:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
EDIT: It's been pointed out that the OP did not ask for JSON, however I find that the answers that recommend just printing or dumping the data into the console provide very little formatting (if any) and are therefore not pretty printing.
I believe that despite the OP not asking for JSON, it is a viable answer as it is a much more readable format for data than the horrendous format that is spat out into the console by xcode/swift.
edited Nov 12 '18 at 12:20
answered May 16 '18 at 13:51
James WolfeJames Wolfe
180214
180214
1
Thanks, With this I was able to pretty print amid debugging viae let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
add a comment |
1
Thanks, With this I was able to pretty print amid debugging viae let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
1
1
Thanks, With this I was able to pretty print amid debugging via
e let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
Thanks, With this I was able to pretty print amid debugging via
e let jsonData = try! JSONSerialization.data(withJSONObject: response, options: .prettyPrinted);if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
– BangOperator
Nov 13 '18 at 9:39
add a comment |
You can just use a for loop and print each iteration
for (key,value) in dictionary {
print("(key) = (value)")
}
Application in extension:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("(key) = (value)")
}
return self.description
}
}
Alternate application:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("(key) = (value)")
}
}
}
Usage:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
Output (Tested in Xcode 8 beta 2 Playground):
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
Since there's adescription
anddebugDescription
already, it might be more appropriate to call the varprettyDescription
and return the formatted string.
– Toland Hon
Aug 4 '16 at 18:43
add a comment |
You can just use a for loop and print each iteration
for (key,value) in dictionary {
print("(key) = (value)")
}
Application in extension:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("(key) = (value)")
}
return self.description
}
}
Alternate application:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("(key) = (value)")
}
}
}
Usage:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
Output (Tested in Xcode 8 beta 2 Playground):
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
Since there's adescription
anddebugDescription
already, it might be more appropriate to call the varprettyDescription
and return the formatted string.
– Toland Hon
Aug 4 '16 at 18:43
add a comment |
You can just use a for loop and print each iteration
for (key,value) in dictionary {
print("(key) = (value)")
}
Application in extension:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("(key) = (value)")
}
return self.description
}
}
Alternate application:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("(key) = (value)")
}
}
}
Usage:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
Output (Tested in Xcode 8 beta 2 Playground):
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
You can just use a for loop and print each iteration
for (key,value) in dictionary {
print("(key) = (value)")
}
Application in extension:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("(key) = (value)")
}
return self.description
}
}
Alternate application:
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("(key) = (value)")
}
}
}
Usage:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
Output (Tested in Xcode 8 beta 2 Playground):
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
edited Aug 4 '16 at 18:10
answered Aug 4 '16 at 17:41
AsdrubalAsdrubal
1,78641933
1,78641933
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
Since there's adescription
anddebugDescription
already, it might be more appropriate to call the varprettyDescription
and return the formatted string.
– Toland Hon
Aug 4 '16 at 18:43
add a comment |
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
Since there's adescription
anddebugDescription
already, it might be more appropriate to call the varprettyDescription
and return the formatted string.
– Toland Hon
Aug 4 '16 at 18:43
1
1
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Is there a reason why you made prettyprint a var instead of just a function?
– Hayden Holligan
Aug 4 '16 at 18:03
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
Honestly, I don't think it matter (I could be wrong). But if you use it a lot then it's less to type in. But raise an interesting question.
– Asdrubal
Aug 4 '16 at 18:08
2
2
Since there's a
description
and debugDescription
already, it might be more appropriate to call the var prettyDescription
and return the formatted string.– Toland Hon
Aug 4 '16 at 18:43
Since there's a
description
and debugDescription
already, it might be more appropriate to call the var prettyDescription
and return the formatted string.– Toland Hon
Aug 4 '16 at 18:43
add a comment |
For Swift 3 (& building on the brilliant answer by @Jalakoo), make the following Dictionary
extension:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
then print a dictionary of any hierarchy in a pretty way (better than dump()
) using this:
print(dictionary!.prettyPrint)
add a comment |
For Swift 3 (& building on the brilliant answer by @Jalakoo), make the following Dictionary
extension:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
then print a dictionary of any hierarchy in a pretty way (better than dump()
) using this:
print(dictionary!.prettyPrint)
add a comment |
For Swift 3 (& building on the brilliant answer by @Jalakoo), make the following Dictionary
extension:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
then print a dictionary of any hierarchy in a pretty way (better than dump()
) using this:
print(dictionary!.prettyPrint)
For Swift 3 (& building on the brilliant answer by @Jalakoo), make the following Dictionary
extension:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
then print a dictionary of any hierarchy in a pretty way (better than dump()
) using this:
print(dictionary!.prettyPrint)
answered Feb 1 '18 at 18:37
AbdelHadyAbdelHady
4,30663668
4,30663668
add a comment |
add a comment |
The methodology of converting the Swift Dictionary to json and back is the neatest. I usually use Facebook's chisel which has a pjson command to print a Swift dictionary.
Eg:
(lldb) pjson dict as NSDictionary
This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested.
P.S.
For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.
add a comment |
The methodology of converting the Swift Dictionary to json and back is the neatest. I usually use Facebook's chisel which has a pjson command to print a Swift dictionary.
Eg:
(lldb) pjson dict as NSDictionary
This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested.
P.S.
For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.
add a comment |
The methodology of converting the Swift Dictionary to json and back is the neatest. I usually use Facebook's chisel which has a pjson command to print a Swift dictionary.
Eg:
(lldb) pjson dict as NSDictionary
This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested.
P.S.
For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.
The methodology of converting the Swift Dictionary to json and back is the neatest. I usually use Facebook's chisel which has a pjson command to print a Swift dictionary.
Eg:
(lldb) pjson dict as NSDictionary
This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested.
P.S.
For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.
answered Apr 14 '18 at 20:39
jarorajarora
3,1322233
3,1322233
add a comment |
add a comment |
How about:
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("(key) = (value)n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
add a comment |
How about:
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("(key) = (value)n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
add a comment |
How about:
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("(key) = (value)n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
How about:
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("(key) = (value)n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
answered Aug 4 '16 at 17:46
BaseZenBaseZen
6,69512138
6,69512138
add a comment |
add a comment |
extension String {
var conslePrintString: String {
guard let data = """
.appending(
replacingOccurrences(of: "\u", with: "\U")
.replacingOccurrences(of: """, with: "\"")
)
.appending(""")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: ,
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\r\n", with: "n")
}
}
let code in extension String and it works fine
let string = "(jsonDictionary)".conslePrintString
add a comment |
extension String {
var conslePrintString: String {
guard let data = """
.appending(
replacingOccurrences(of: "\u", with: "\U")
.replacingOccurrences(of: """, with: "\"")
)
.appending(""")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: ,
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\r\n", with: "n")
}
}
let code in extension String and it works fine
let string = "(jsonDictionary)".conslePrintString
add a comment |
extension String {
var conslePrintString: String {
guard let data = """
.appending(
replacingOccurrences(of: "\u", with: "\U")
.replacingOccurrences(of: """, with: "\"")
)
.appending(""")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: ,
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\r\n", with: "n")
}
}
let code in extension String and it works fine
let string = "(jsonDictionary)".conslePrintString
extension String {
var conslePrintString: String {
guard let data = """
.appending(
replacingOccurrences(of: "\u", with: "\U")
.replacingOccurrences(of: """, with: "\"")
)
.appending(""")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: ,
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\r\n", with: "n")
}
}
let code in extension String and it works fine
let string = "(jsonDictionary)".conslePrintString
edited Oct 11 '17 at 1:59
Toland Hon
3,04712233
3,04712233
answered Sep 5 '17 at 15:58
hasayakeyhasayakey
864
864
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38773979%2fis-there-a-way-to-pretty-print-swift-dictionaries-to-the-console%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
You could use
dump
, for example, if the goal is to inspect the dictionary. stackoverflow.com/documentation/swift/3966/logging-in-swift/…– Moritz
Aug 4 '16 at 17:39
12
print(dictionary as! NSDictionary)
cheap trick?– BaseZen
Aug 4 '16 at 17:41
I really the the dump() suggestion since it doesn't require to write any code or cast it. @EricAya, if you post an answer with that remark, I'll mark it as the answer.
– Toland Hon
Aug 4 '16 at 18:35
1
@TolandHon Done. I've made an answer with an example of the output.
– Moritz
Aug 4 '16 at 18:52