我使用命令行创建swift文件,并使用swift命令为了运行其中之一。但是,我想要一个文件能够从另一个文件访问函数。如果这是C,那么我可以使用#include宏并指定文件的位置。但Swift的import语句似乎不允许这样。应该有办法,我想知道如何做。
I am using the command line to create swift files and using the "swift" command in order to run one of them. However I would like one file to be able to access functions from another file. If this were C then I could use the #include macro and specify where the file is. But Swift's import statement doesn't seem to allow that. There should be a way and I would like to know how to do it.
例如:
我有一个文件与一个功能,然后我做另一个文件,使用该功能。如何允许它使用它?
If I have a file with a function in it and then I make another file that uses that function. How do I allow it to use it?
// file1.swift import Foundation func sayHello() -> String { return "hello" } // file2.swift import file1 // <-- trying to import file1 but it doesn't work println(sayHello())然后在终端中写swift file2.swift。但它告诉我..
Once the files have been made I then write "swift file2.swift" in terminal. But it tells me..
error: no such module 'file1.swift'很明显swift编译器正在寻找一个模块。如何使file1成为一个模块?我看到一些解决方案,但他们都发生在Xcode。
clearly the swift compiler is looking for a module. How do I make file1 into a module? I've seen some solutions but they all take place in Xcode. What I'm looking for is to do it all in the command line.
推荐答案// file1.swift func sayHello() -> String { return "hello" } // main.swift println(sayHello())
,然后从终端:
$ swiftc file1.swift main.swift $ ./main hello更多推荐
如何在Swift中导入没有Xcode项目的模块
发布评论