Search code examples
swiftlldb

Python's dir() and help() equivalents in Swift REPL


Just installed Swift on Ubuntu and was pleasantly surprised that executing swift runs a language shell (aka REPL), similar to Python's interactive shell.

To get a feel of the Swift language, which is new to me, I wanted to declare a few objects and see what methods they provide. In Python this is achieved by built-in function dir(object), which returns names of attributes of an object. If you call it without arguments, it returns the list of variable and module names in the current local scope. – Both of these behaviors are very useful in the shell.

Python shell also has a very useful help() function, which invokes the built-in help system. By calling help(object), you can read Python reference on the class of the object.

Are there any equivalents of Python's help() and dir() inside Swift REPL?

More specifically:

  • Can I get the list of currently declared variables?
  • Can I see the list of object methods in the shell (REPL)?
  • Can I read object reference in the shell?

(If it helps, I have Swift version 4.2.1, LLDB version 6.0.0)


Solution

  • Swift doesn't have the methods like help() but you can use the lldb commands. you can input : in Swift REPL for the shell to switch to LLDB mode.

    Can I see the list of object methods in the shell (REPL)?
    type lookup ClassNameOfInstance

    Can I get the list of currently declared variables?
    image lookup -rs lldb_expr

    Can I read object reference in the shell?
    expression -l swift -- instanceName

    use c command to exit LLDB mode.

    addition:

    • When you define a variables in Swift REPL, Swift Repl make modules such as $__lldb_expr2, $__lldb_expr3 for each.

    • If you would like to know lldb commands, you can use help command in lldb mode.