What is the equivalent for swift REPL of Python's python -i thisfiletoload.py?

250 views Asked by At

What is the equivalent for swift REPL of Python's python -i thisfiletoload.py ? Thanks. i.e.

python -i thisfiletoload.py

in the command prompt. What's the swift REPL equivalent?

2

There are 2 answers

0
JAL On

Swift used to have a -i "input" flag, but that flag is deprecated and no longer necessary.

Running swift [file.swift] from the command line will result in the behavior you desire.

test.swift:

println("hello")
let x = 1
println("x = \(x)")

Console Output:

➜  Test  swift test.swift
hello
x = 1

With -i:

➜  Test  swift -i test.swift
<unknown>:0: error: the flag '-i' is no longer required and has been removed; use 'swift input-filename'

Version:

➜  Test  swift --version
Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)
Target: x86_64-apple-darwin14.3.0
0
ideasuns On

I've only been able to accomplish this by first converting the file into a module.

$ swiftc filename.swift -emit-library -sdk $( xcrun --sdk macosx --show-sdk-path) -emit-module -module-link-name MyCode -module-name MyCode -lSystem

That will compile your file, and create a .dylib and .swiftmodule in the current directory ( to which you must of course have read-write access). Then, from that same directory, just:

$ swift -L. -I.

Welcome to Apple Swift version 5.2.2 (swiftlang-1103.0.32.6 clang-1103.0.32.51). Type :help for assistance.

1> import MyCode

2> /// Begin using your module's code...


As a .bashrc function you could:

repl_mod () {
    SDK=$( xcrun --sdk macosx --show-sdk-path)
    MODNAME=${1%.swift}
    $( xcrun -f swiftc) $1 -emit-library -sdk $SDK -emit-module -module-link-name $MODNAME -module-name $MODNAME -lSystem
}

Which would produce a module in the current directory, named after your filename:

repl_mod mycode.swift

swift -L. -I. ...

>1 import mycode

If you modify the command to output its results somewhere other than the current directory, be sure to convey that change to the REPL via the -L and -I args.