2016-08-04 182 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)