如何在调试时打印Swift结构的自定义描述,而不是其他内容?

时间:2016-01-20 18:18:20

标签: xcode swift

说我有这样的结构:

struct MyStruct: CustomStringConvertible {
    let myInt: Int
    let myString: String

    var description: String {
        return "my int is \(myInt),\nand my string is \"\(myString)\""
    }
}

从代码中打印描述可以正常工作。

let myStruct = MyStruct(myInt: 3, myString: "hello")
print(myStruct)

这导致

my int is 3,
and my string is "hello"

当我想从调试器中打印myStruct的描述时出现问题。 po myStruct导致

▿ my int is 3,
and my string is "hello"
  - myInt : 3
  - myString : "hello"

明确打印出其描述并不会有任何帮助,因为po myStruct.description会导致

"my int is 3,\nand my string is \"hello\""

我认为这可能与CustomDebugStringConvertible有关,所以我添加了以下代码:

extension MyStruct: CustomDebugStringConvertible {
    var debugDescription: String {
        return description
    }
}

不幸的是,这并没有改变任何结果。

有没有办法让

my int is 3,
and my string is "hello"
调试时从命令行打印?

1 个答案:

答案 0 :(得分:2)

(lldb) expression print(myStruct)
my int is 3,
and my string is "hello"

你可以定义自己的'命令'

(lldb) help command
The following subcommands are supported:

      alias   -- Allow users to define their own debugger command
                 abbreviations.  This command takes 'raw' input (no need to
                 quote stuff).
      delete  -- Allow the user to delete user-defined regular expression,
                 python or multi-word commands.
      history -- Dump the history of commands in this session.
      regex   -- Allow the user to create a regular expression command.
      script  -- A set of commands for managing or customizing script commands.
      source  -- Read in debugger commands from the file <filename> and execute
                 them.
      unalias -- Allow the user to remove/delete a user-defined command
                 abbreviation.