How to Import modules without an Xcode project in Swift

五迷三道 提交于 2019-12-21 04:19:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!