Introduction to Swift REPL
You can also read the full story on The Swift Nerd blog using the link below:
A read–eval–print loop (REPL) ( also called language shell ) is a simple, interactive computer programming environment that
- Takes single user inputs (i.e., single expressions),
- Evaluates (executes) them
- Prints the result to the user
Swift REPL is built on LLDB and Xcode playgrounds are built on it.
Read why REPL is amazing here.
How to launch REPL?
You can get to the Swift REPL by either through XCode debugger console or terminal
Terminal
To launch REPL, open terminal and enter xcrun swift
Pro tip: You can even declare your functions inside it and call them to get results
Xcode Debugger console
You can pause debugger on a breakpoint and hit repl command in the debug console.
Pro tip: You can switch to LLDB by entering colon(:), and back to REPL using repl.
Xcode playgrounds
Xcode playgrounds are a modern version of Swift REPL. That’s why you are able to run and debug a section of code in the playgrounds. The REPL reads the contents of playgrounds, evaluates the expressions, and displays the output in the results panel on the right.
However, REPL and Xcode playgrounds can have different use cases as REPL is a full-featured debugger. You can use REPL to inject code in your codebase to see the result while working in your Xcode project, which might not be possible with playground(Unless you copy all of your project code in. the playground!).
The Swift REPL allows you to import the core libraries like Foundation
, Dispatch
and system modules like Darwin
on macOS and Glibc
on Linux. In fact, the REPL allows you to import any Swift module as long as it can correctly find and load them using the compiler arguments that are provided while launching the REPL. Source: Swift docs.
Thank you for reading. If you liked this article and found it useful, share and spread it like wildfire!
You can find me on LinkedIn | Github | StackOverflow