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

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


        
16条回答
  •  猫巷女王i
    2020-12-07 10:23

    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
    

提交回复
热议问题