Swift: How do I enter interactive mode during/after running code with the Swift interpreter?

Created on 23 Nov 2019  Â·  5Comments  Â·  Source: tensorflow/swift

In Python, you can use the code module to set interactive breakpoints in in a piece of code. You can also enter interactive mode after a script is complete by running python -i main.py.

I imagine there is some way to do this with Swift, too, maybe with LLDB. But I'm having trouble finding it. How can I replicate this common Python workflow with Swift?

Most helpful comment

I'm not aware of options on the Swift REPL that do exactly this. There are some similar things you can do though.

If you're in a SwiftPM package, you can import that package into the repl using swift run --repl: https://swift.org/blog/swiftpm-repl-support/

You could also try cat script.swift - | swift to pipe the script into the repl so that it executes all the commands and then lets you enter commands. Unfortunately the REPL prompt and autocomplete don't work when stdin is being piped through cat. Not sure if there's a way around this.

All 5 comments

I'm not aware of options on the Swift REPL that do exactly this. There are some similar things you can do though.

If you're in a SwiftPM package, you can import that package into the repl using swift run --repl: https://swift.org/blog/swiftpm-repl-support/

You could also try cat script.swift - | swift to pipe the script into the repl so that it executes all the commands and then lets you enter commands. Unfortunately the REPL prompt and autocomplete don't work when stdin is being piped through cat. Not sure if there's a way around this.

Thanks! I've been able to get your second suggestion working with good results.

I'm working with a SwiftPM package right now, too, and ran into an issue with swift run --repl. I'm getting Error: unable to synthesize a REPL product as there are no library targets in the package. I imagine I must have something configured wrong — very new to SwiftPM.

also, I'll note that I'm using Ubuntu 19.04 and the 0.7 toolchain.

I'm working with a SwiftPM package right now, too, and ran into an issue with swift run --repl. I'm getting Error: unable to synthesize a REPL product as there are no library targets in the package. I imagine I must have something configured wrong — very new to SwiftPM.

Based on these docs I think the problem lies in your targets being executable, rather than libraries (they'll be executable if the module contains a main.swift). I had the same problem using the repl - dropping main.swift from the package solved it (you can then import your module)

One thing to note: the command line REPL is unsupported currently. We do support Jupyter / Colab, and you can install / import your packages. Check out: https://github.com/google/swift-jupyter for additional documentation & details, or just fire up a blank notebook.

Was this page helpful?
0 / 5 - 0 ratings