【问题标题】:What is the equivalent for swift REPL of Python's python -i thisfiletoload.py?Python 的 python -i thisfiletoload.py 的 swift REPL 的等价物是什么?
【发布时间】:2015-08-31 05:08:55
【问题描述】:

Python 的 python -i thisfiletoload.py 的 swift REPL 的等价物是什么?谢谢。即

python -i thisfiletoload.py

在命令提示符下。 swift REPL 等价物是什么?

【问题讨论】:

  • 我的回答对您有帮助吗?如果有,请将其标记为已接受。
  • 没有。当我在命令提示符下键入 swift [file.swift] 时,在 swift 文件运行后,它会返回到命令提示符,而不是与声明的所有变量一起留在 REPL。

标签: swift read-eval-print-loop interactive-mode


【解决方案1】:

Swift 曾经有一个 -i "input" 标志,但该标志已被弃用且不再需要。

从命令行运行swift [file.swift] 将产生你想要的行为。

test.swift:

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

控制台输出:

➜  Test  swift test.swift
hello
x = 1

-i:

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

版本:

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

【讨论】:

    【解决方案2】:

    我只能通过首先将文件转换为模块来完成此操作。

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

    这将编译您的文件,并在当前目录中创建一个 .dylib 和 .swiftmodule(您当然必须具有读写权限)。然后,从同一个目录中,只需:

    $ swift -L. -I.

    欢迎使用 Apple Swift 版本 5.2.2 (swiftlang-1103.0.32.6 clang-1103.0.32.51)。 输入 :help 寻求帮助。

    1> import MyCode

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


    作为 .bashrc 函数,您可以:

    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
    }
    

    这将在当前目录中生成一个以您的文件名命名的模块:

    repl_mod mycode.swift

    swift -L. -I. ...

    >1 import mycode

    如果您修改命令以在当前目录以外的位置输出其结果,请务必通过 -L-I 参数将该更改传达给 REPL。

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 1970-01-01
      • 2011-09-03
      • 2011-03-07
      • 2011-12-18
      • 2013-10-18
      • 2019-04-02
      • 2012-03-20
      • 1970-01-01
      相关资源
      最近更新 更多