[ios] Swift 사전을 콘솔에 예쁘게 인쇄하는 방법이 있습니까?

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

콘솔에 다음을 인쇄합니다.

{
    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"]

Swift에서 각 키-값 쌍이 새 줄을 차지하는 예쁜 인쇄 사전으로 가져 오는 방법이 있습니까?



답변

예를 들어 목표가 사전을 검사하는 경우 dump를 사용할 수 있습니다 . dumpSwift의 표준 라이브러리의 일부입니다.

용법:

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

dump(dictionary)

산출:

여기에 이미지 설명 입력


dump 반사 (미러링)를 통해 개체의 내용을 인쇄합니다.

어레이 상세보기 :

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

인쇄물:

▿ 4 개 요소
-[0] : Joe-
[1] : Jane-
[2] : Jim-
[3] : Joyce

사전의 경우 :

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

인쇄물:

▿ 키 / 값 쌍 3 개
▿ [0] : (2 개 요소)
– .0 : bar
-.1 : 33
▿ [1] : (2 개 요소)
-.0 : baz
-.1 : 42
▿ [2] : ( 2 요소)
-.0 : foo
-.1 : 10

dump 다음과 같이 선언됩니다. dump(_:name:indent:maxDepth:maxItems:) .

첫 번째 매개 변수에는 레이블이 없습니다.

name검사중인 객체의 레이블을 설정하는 것과 같은 다른 매개 변수를 사용할 수 있습니다 .

dump(attributes, name: "mirroring")

인쇄물:

▿ 미러링 : 3 개의 키 / 값 쌍
▿ [0] : (2 개 요소)
– .0 : bar
-.1 : 33
▿ [1] : (2 개 요소)
-.0 : baz
-.1 : 42
▿ [2] : (2 요소)
-.0 : foo
-.1 : 10

을 사용하여 특정 수의 항목 만 인쇄 maxItems:하고를 사용하여 특정 깊이까지 개체를 구문 분석 maxDepth:하고을 사용하여 인쇄 된 개체의 들여 쓰기를 변경 하도록 선택할 수도 있습니다 indent:.


답변

사전을 ‘AnyObject’로 캐스팅하는 것이 저에게 가장 간단한 해결책이었습니다.

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

이것은 콘솔 출력입니다

이것은 덤프 옵션보다 읽기 쉽지만 총 키-값 수를 제공하지는 않습니다.


답변

PO 솔루션

콘솔 에서 이스케이프 시퀀스가없는 JSON으로 Dictionary를보고 싶은 분 여기에 간단한 방법이 있습니다.

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


답변

함수형 프로그래밍을 사용하는 또 다른 방법

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

산출

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


답변

디버그 목적으로 만 Array 또는 Dictionary를 예쁜 인쇄 된 json으로 변환합니다.

public extension Collection {

    /// Convert self to JSON String.
    /// Returns: the pretty printed JSON string or an empty string if any error occur.
    func json() -> String {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
            return String(data: jsonData, encoding: .utf8) ?? "{}"
        } catch {
            print("json serialization error: \(error)")
            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
}


답변

JSON 유효성 검사기에 결과를 전달할 때 결과가 유효하지 않기 때문에 여기에 제공된 많은 답변을 고려하지 않을 것입니다 (종종 ‘:’이 아닌 ‘=’를 포함하는 코드로 인해).

내가 찾은 가장 쉬운 방법은 예쁜 인쇄 된 쓰기 옵션을 사용하여 JSON 객체를 데이터로 변환 한 다음 결과 데이터를 사용하여 문자열을 인쇄하는 것입니다.

다음은 그 예입니다.

let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

if let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}

결과:

{
    "jsonData": [
        "Some String"
    ],
    "moreJSONData": "Another String",
    "evenMoreJSONData": {
        "A final String": "awd"
    }
}

편집하다 : OP가 JSON을 요청하지 않았다고 지적되었지만 데이터를 콘솔에 인쇄하거나 덤프하는 것을 권장하는 답변은 (있는 경우) 매우 적은 형식을 제공하므로 예쁜 인쇄가 아닙니다.

나는 OP가 JSON을 요구하지 않음에도 불구하고 xcode / swift에 의해 콘솔에 튀어 나온 끔찍한 형식보다 데이터에 대해 훨씬 더 읽기 쉬운 형식이므로 실행 가능한 대답이라고 생각합니다.


답변

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 베타 2 플레이 그라운드에서 테스트 됨) :

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