po in LLDB with swift

后端 未结 4 1487
无人及你
无人及你 2020-12-13 04:26

How can I plot out variable\'s value in a Swift App with LLDB?

Earlier it was like po variable_name

Now I usually get some nasty error, like:

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 04:44

    I have made a few tests to figure out how it works with Swift, results surprised me a bit. With ObjC objects po calls debugDescription which by default calls description. That is clear. Unfortunately the same doesn't apply while working with Swift classes. I focused on objects rather than on printing single variables.

    To make it working (po command in lldb) I had to override description. Below code I used for testing:

    class Test : NSObject
    {
        var name : String?
        var surname : String?
    
        override var debugDescription : String{
            return "debugDescription method"
        }
    
        override var description : String {
            return "description Method"
        }
    }
    

    Testing:

    let test = Test()
    test.name = "name"
    test.surname = "surname"
    
    (lldb) po test
    description Method
    
    (lldb) p test
    (DebugTest.Test) $R1 = 0x00007fce11404860 {
      ObjectiveC.NSObject = {
        isa = DebugTest.Test
      }
      name = "name"
      surname = "surname"
    }
    
    (lldb) po dump(test)
    ▿ DebugTest.Test #0
      - super: debugDescription method
      ▿ name: name
        - Some: name
      ▿ surname: surname
        - Some: surname
    description Method
    
    (lldb) po print(test)
    description Method
    

    The thing that surprised me is that po on Swift objects calls description rather than debugDescription that differs from ObjC.

    EDIT

    To make it acting like with ObjC, Your class have to implement CustomDebugStringConvertible and then po will call debugDescription, which by default calls description. The only thing which have to be changed in my example would be adding:

    class Test : NSObject, CustomDebugStringConvertible
    

    Reference

    Checked with XCode 7.0.1 and iOS SDK 9, Swift 2.0

提交回复
热议问题