【问题标题】:How to include .swift file from other .swift file in an immediate mode?如何以即时模式包含其他 .swift 文件中的 .swift 文件?
【发布时间】:2014-08-16 18:59:09
【问题描述】:

拥有一个函数定义为bar.swift的文件:

func bar() {
    println("bar")
}

还有一个以即时模式运行的脚本foo.swift

#!/usr/bin/xcrun swift -i
bar()

如何从foo.swift 导入bar.swiftbar() 函数?

【问题讨论】:

  • 首先你应该使用#!/usr/bin/swift而不是xcrun。
  • @AbhiBeckert:我认为这取决于操作系统。在 OS X 10.9 上,您必须使用 xcrun。 10.10 可以直接调用 swift/swiftc。

标签: swift immediate-mode


【解决方案1】:

我认为现在的答案是,除非您编译代码,否则您不能将代码拆分到多个文件中。使用#!/usr/bin/swift 执行仅适用于单个文件脚本。

http://bugreport.apple.com/ 提交增强请求显然是个好主意,但同时您必须在执行代码之前对其进行编译。

另外,您的foo.swift 文件不能使用该名称,您必须将其重命名为main.swift。如果有多个文件被编译,那么只有main.swift 被允许在顶层有代码。

所以,你有这两个文件:

main.swift:

bar()

bar.swift:

func bar() {
    println("bar")
}

然后编译/执行代码:

$ swiftc main.swift bar.swift -o foobar

$ ./foobar 
bar

如果你所有的 swift 文件都在同一个目录下,你可以缩短编译命令:

$ swiftc *.swift -o foobar

或者如果你想搜索子目录:

$ find . -iname '*.swift' | xargs swiftc -o foobar

【讨论】:

  • 谢谢,为我工作。出于某种原因,我没有安装swiftc,但以上所有内容也适用于xcrun swiftc
  • @Thilo 确保您从 App Store 获得了最新版本的 Xcode,然后在终端中运行 xcode-select --install。在那之后你应该有swiftc。当我尝试使用您正在使用的代码时,我收到一个编译错误,指出不再允许使用语法。所以你显然在运行旧版本。
【解决方案2】:

编写一个 bash 脚本来连接文件。下面的脚本在执行之前将库文件预先添加到脚本的前面:

#!/bin/bash

cat $HOME/my_swift/my_library_to_add.swift $1.swift > t.swift
swift t.swift

由于生成的文件是一次性文件,您可以将其放在 RAM 驱动器上。这是根据需要创建或重复使用微型 1 Mb RAM 驱动器的更高级版本。

if [ ! -d /Volumes/swift_buffer ]; then
   diskutil erasevolume HFS+ 'swift_buffer' `hdiutil attach -nomount ram://2048`
fi

cat $HOME/my_swift/my_library_to_add.swift $1.swift > /Volumes/swift_buffer/t.swift   
swift /Volumes/swift_buffer/t.swift

这将创建一个容量仅为 1 Mb 的微型 RAM 驱动器,足以容纳任何实用程序脚本和简单的库。

已安装的 RAM 驱动器将在 Finder 中可见,可以从中弹出。我没有直接在脚本中处理它,因为分配需要时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多