How to include .swift file from other .swift file in an immediate mode?

前端 未结 2 1895
刺人心
刺人心 2020-12-05 07:17

Having a file with function definition bar.swift:

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

And a script to be run in immediate mode

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 08:20

    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.

    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.

    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:

    bar()
    

    bar.swift:

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

    And compile/execute the code with:

    $ swiftc main.swift bar.swift -o foobar
    
    $ ./foobar 
    bar
    

    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
    

提交回复
热议问题