Is there a way to pretty print Swift dictionaries to the console?

前端 未结 16 981
北海茫月
北海茫月 2020-12-07 09:33
NSDictionary *dictionary = @{@\"A\" : @\"alfa\",
                             @\"B\" : @\"bravo\",
                             @\"C\" : @\"charlie\",
                       


        
16条回答
  •  隐瞒了意图╮
    2020-12-07 10:23

    Details

    • Xcode 10.2.1 (10E1001), Swift 5

    Solution

    extension Dictionary {
        func format(options: JSONSerialization.WritingOptions) -> Any? {
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
                return try JSONSerialization.jsonObject(with: jsonData, options: [.allowFragments])
            } catch {
                print(error.localizedDescription)
                return nil
            }
        }
    }
    

    Usage

    let dictionary: [String : Any] = [
                                        "id": 0,
                                        "bool": true,
                                        "int_array": [1,3,5],
                                        "dict_array": [
                                            ["id": 1, "text": "text1"],
                                            ["id": 1, "text": "text2"]
                                        ]
                                     ]
    print("Regualr print:\n\(dictionary)\n")
    guard let formatedDictionary = dictionary.format(options: [.prettyPrinted, .sortedKeys]) else { return }
    print("Pretty printed:\n\(formatedDictionary)\n")
    

    Results

提交回复
热议问题