Created
October 5, 2015 21:01
-
-
Save IanKeen/54a5c049bca42030811a to your computer and use it in GitHub Desktop.
A 'alternative' way to print out dictionaries and arrays in Swift if you don't like the default output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Usage: toString(object) | |
*/ | |
public func toString(object: AnyObject) -> String { | |
return toString(any: object, indent: 0) | |
} | |
private func indented(count: Int, string: String) -> String { | |
return String(count: count, repeatedValue: Character("\t")) + string | |
} | |
private func toString(array array: [AnyObject], indent: Int) -> String { | |
var result = indented(indent, string: "[\r\n") | |
array.forEach { result += toString(any: $0, indent: indent + 1) } | |
result += indented(indent, string: "]\r\n") | |
return result | |
} | |
private func toString(dictionary dictionary: [String: AnyObject], indent: Int) -> String { | |
var result = indented(indent, string: "{\r\n") | |
dictionary.forEach { key, value in | |
result += indented(indent+1, string: "\(key):") | |
result += toString(any: value, indent: indent+1) | |
} | |
result += indented(indent, string: "}\r\n") | |
return result | |
} | |
private func toString(any any: AnyObject, indent: Int) -> String { | |
var result = "" | |
if (any is [AnyObject]) { | |
result += toString(array: (any as! [AnyObject]), indent: indent) | |
} else if (any is [String: AnyObject]) { | |
result += toString(dictionary: (any as! [String: AnyObject]), indent: indent) | |
} else { | |
result += indented(indent, string: "\(any)\r\n") | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment