How to Import modules without an Xcode project in

2019-03-26 15:41发布

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.

2条回答
Lonely孤独者°
2楼-- · 2019-03-26 16:15
// file1.swift
func sayHello() -> String {
    return "hello"
}

// main.swift
println(sayHello())

and then from the terminal:

$ swiftc file1.swift main.swift 
$ ./main 
hello
查看更多
贼婆χ
3楼-- · 2019-03-26 16:22

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.

查看更多
登录 后发表回答