问题
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.
for example:
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())
Once the files have been made I then write "swift file2.swift" in terminal. But it tells me..
error: no such module 'file1.swift'
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.
回答1:
// file1.swift
func sayHello() -> String {
return "hello"
}
// main.swift
println(sayHello())
and then from the terminal:
$ swiftc file1.swift main.swift
$ ./main
hello
回答2:
See http://computers.tutsplus.com/tutorials/alfred-workflows-in-swift--cms-21807 for an example of creating a module (an Alfred helper library) from the command line, also http://www.alfredforum.com/topic/4902-alfred-workflows-in-swift-tutorial-is-available/?p=35662 where the author of the tutorial explains the four step compilation process in more detail.
来源:https://stackoverflow.com/questions/29089861/how-to-import-modules-without-an-xcode-project-in-swift