2016-08-04 66 views
27
NSDictionary *dictionary = @{@"A" : @"alfa", 
          @"B" : @"bravo", 
          @"C" : @"charlie", 
          @"D" : @"delta", 
          @"E" : @"echo", 
          @"F" : @"foxtrot"}; 
NSLog(@"%@", dictionary.description); 

打印出的控制台上执行以下操作:有没有办法将Swift字典漂亮地打印到控制台?

{ 
    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) 

打印出的控制台上执行以下操作:

["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"] 

是否有斯威夫特的方式来得到它漂亮的打印字典,其中每个键 - 值对占据一个新的行?

+4

,你可以例如,如果目标是检查字典,则使用'dump'。 http://stackoverflow.com/documentation/swift/3966/logging-in-swift/14168/dump – Moritz

+10

'print(dictionary as!NSDictionary)'cheap trick? – BaseZen

+0

我真的是转储()的建议,因为它不需要写任何代码或转换它。 @EricAya,如果你发表了这个评论的答案,我会将其标记为答案。 –

回答

46

例如,如果目标是检查字典,则可以使用dumpdump是Swift标准库的一部分。

用法:

let dictionary: [String : String] = ["A" : "alfa", 
            "B" : "bravo", 
            "C" : "charlie", 
            "D" : "delta", 
            "E" : "echo", 
            "F" : "foxtrot"] 

dump(dictionary) 

输出:通过反射

enter image description here


dump打印的对象的内容(镜像)。

阵列的详细视图:

let names = ["Joe", "Jane", "Jim", "Joyce"] 
dump(names) 

打印:

▿4元件
- [0]:乔
- [1]:简
- [2] :Jim
- [3]:Joyce

对于词典:

let attributes = ["foo": 10, "bar": 33, "baz": 42] 
dump(attributes) 

打印:

▿3键/值对
▿[0]:(2种元素)
- 0.0:巴
- 0.1 :33
▿[1]:(2种元素)
- 0.0:巴兹
- 0.1:42
▿[2]:(2种元素)
- 0.0:FOO
- 0.1:10

dump被声明为dump(_:name:indent:maxDepth:maxItems:)

第一个参数没有标签。

还有其他参数可用,像name设置为对象的标签被检查:

dump(attributes, name: "mirroring") 

打印:

▿镜像:3的键/值对
▿[0] :(2个元素)
- .0:bar
- .1:33
[1] :(2个元素)
- 0.0:巴兹
- 0.1:42
▿[2]:(2种元素)
- 0.0:FOO
- 0.1:10

还可以选择,以用​​仅打印一定数量的项目,以maxDepth:解析对象达到一定深度,并用indent:更改打印对象的缩进。

3

您可以只使用一个for循环和打印扩展每次迭代

for (key,value) in dictionary { 
    print("\(key) = \(value)") 
} 

应用:

extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible { 

    var prettyprint : String { 
     for (key,value) in self { 
      print("\(key) = \(value)") 
     } 

     return self.description 
    } 
} 

替代应用:

extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible { 

    func prettyPrint(){ 
     for (key,value) in self { 
      print("\(key) = \(value)") 
     } 
    } 
} 

用法:

dictionary.prettyprint //var prettyprint 
dictionary.prettyPrint //func prettyPrint 

输出(测试在Xcode 8 Beta 2的游乐场):

A = alfa 
B = bravo 
C = charlie 
D = delta 
E = echo 
F = foxtrot 
+1

是否有一个原因,你为什么漂亮打印一个var而不是一个函数? –

+0

老实说,我不认为这很重要(我可能是错的)。但是,如果你使用它很多,那么键入内容就会减少。但提出一个有趣的问题。 – Asdrubal

+2

由于已经有'description'和'debugDescription',所以调用var'prettyDescription'并返回格式化的字符串可能更合适。 –

0

如何:

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) 
22

又一个使用函数式编程方式

dictionary.forEach { print("\($0): \($1)") } 

输出

B: bravo 
A: alfa 
F: foxtrot 
C: charlie 
D: delta 
E: echo 
+1

这应该是最佳答案。完美的作品! –

+0

或更“功能性”... dictionary.map {“\($ 0):\($ 1)”} .forEach(print) (舌尖评论) –

+0

这适用于OP '[String:String]'字典,但对于[AnyHashable:Any]字典来说并不好,如果值是一个字典,那么你就回到了Swift的非漂亮打印。 –

13

对于调试目的仅我转换Array或字典到一个相当印刷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 "{}" 
     } 
    } 
} 

然后:

print("\nHTTP request: \(URL)\nParams: \(params.json())\n") 

上控制台结果:

HTTP request: https://example.com/get-data 
Params: { 
    "lon" : 10.8663676, 
    "radius" : 111131.8046875, 
    "lat" : 23.8063882, 
    "index_start" : 0, 
    "uid" : 1 
} 
+0

这是什么bLog? – Nitesh

+0

@Nitesh bLog是一个带有backtrace的简单自定义记录器,我用print()编写了它。 –

27

SWIFT 3

C asting字典来“AnyObject”最简单的办法对我来说:

let dictionary = ["a":"b", 
         "c":"d", 
         "e":"f"] 
    print("This is the console output: \(dictionary as AnyObject)") 

enter image description here

这是很容易,转储选项读给我,但要注意它不会给你钥匙的总数 - 值。

+1

酷,但我不明白为什么它的工作。 – kelin

+0

这是一个比倾倒更好的方式和方式 – AbdelHady

0
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 
8

口服溶液

对于那些希望看到词典作为JSON用了转义序列中控制台,这里有一个简单的方法来做到这一点

(LLDB)po print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8)!)

3

对于斯威夫特3(&建立在辉煌的答案@Jalakoo),进行以下Dictionary扩展:使用

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any { 
    var prettyPrint: String { 
     return String(describing: self as AnyObject) 
    } 
} 

然后打印字典任何层次漂亮方式(优于dump())这样的:

print(dictionary!.prettyPrint) 
相关问题