관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] dump 사용 방법 본문

iOS 응용 (swift)

[iOS - swift] dump 사용 방법

jake-kim 2023. 6. 1. 01:59

Dump 개념 

  • mirror를 사용하여 객체를 출력하는 것
  • 객체의 프로퍼티들에 접근하면서 프린트를하며, 재귀적으로 안에 있는 객체들도 같은 방법으로 프린트 (standard output)

https://developer.apple.com/documentation/swift/dump(_:name:indent:maxdepth:maxitems:)

  • dump 함수 파라미터
    • value: 프로퍼티 값들을 출력할 객체
    • name: 해당 dump의 이름
    • indent: 출력될때 왼쪽 여백 인덴트값
    • maxDepth: 객체안에 객체가 또 있을 때 그 깊이
    • maxitems: 출력할 라인수
  • dump 예제
struct Price {
    var value: Int
}

let price = Price(value: 1)

print(price)
// Price(value: 1)

dump(price)
/*
▿ __lldb_expr_18.Price
  - value: 1
*/

dump는 언제 사용하면 좋을까?

  • print도 있지만 dump가 따로 있는 이유는 객체 안의 객체를 출력할 때 파악하기가 쉬움

ex) 아래처럼 모델이 여러개가 nested 되어 있을 때 dump로 출력하면 데이터 파악하기가 용이

struct Person {
    var name: String
    var age: Int
    var address: Address
}

struct Address {
    var street: String
    var city: String
    var price: Price
}

struct Price {
    var value: Int
}

let person = Person(
    name: "John",
    age: 30,
    address: Address(
        street: "123 Main St",
        city: "New York",
        price: .init(value: 2)
    )
)
  • print vs dump 비교
print(person)
// Person(name: "John", age: 30, address: __lldb_expr_18.Address(street: "123 Main St", city: "New York", price: __lldb_expr_18.Price(value: 2)))

dump(person, name: "jake")
/*
▿ jake: __lldb_expr_20.Person
  - name: "John"
  - age: 30
  ▿ address: __lldb_expr_20.Address
    - street: "123 Main St"
    - city: "New York"
    ▿ price: __lldb_expr_20.Price
      - value: 2
*/
  • dump는 또 class 인스턴스를 출력할 때도 유용
    • class 인스턴스를 print사용하여 출력하면 인스턴스 이름만 출력되지만, dump는 안의 프로퍼티 값들도 같이 출력됨
class ABC {
    var a = 0
    var b = DEF()
}

class DEF {
    var b = 1
}

let abc = ABC()

print(abc)
// __lldb_expr_20.ABC

dump(abc)
/*
▿ __lldb_expr_20.ABC #0
  - a: 0
  ▿ b: __lldb_expr_20.DEF #1
    - b: 1
*/

* 참고

https://developer.apple.com/documentation/swift/dump(_:name:indent:maxdepth:maxitems:) 

Comments