如何以立即模式包含来自其他 .swift 文件的 .swift 文件? [英] How to include .swift file from other .swift file in an immediate mode?

查看:25
本文介绍了如何以立即模式包含来自其他 .swift 文件的 .swift 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Having a file with function definition bar.swift:

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

以及一个在立即模式下运行的脚本 foo.swift:

And a script to be run in immediate mode foo.swift:

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

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

How do you import bar.swift's bar() function from foo.swift?

推荐答案

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

I think the answer right now is that you can't split code across multiple files unless you compile the code. Executing with #!/usr/bin/swift is only possible for single file scripts.

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

It's obviously a good idea to file an enhancement request at http://bugreport.apple.com/, but in the mean time you're going to have to compile the code before executing it.

另外,你的 foo.swift 文件不能有那个名字,你必须把它重命名为 main.swift.如果有多个文件被编译,那么只有 main.swift 被允许在顶层有代码.

Also, your foo.swift file cannot have that name, you have to rename it to main.swift. If there are multiple files being complied, then only main.swift is allowed to have code at the top level.

所以,你有这两个文件:

So, you have these two files:

main.swift:

main.swift:

bar()

bar.swift:

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

并编译/执行代码:

$ swiftc main.swift bar.swift -o foobar

$ ./foobar 
bar

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

If all your swift files are in the same directory, you could shorten the compile command:

$ swiftc *.swift -o foobar

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

Or if you want to search child directories:

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

这篇关于如何以立即模式包含来自其他 .swift 文件的 .swift 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆