swift build use of unresolved identifier

2.1k views Asked by At

I used vapor to build a project. create a swift file using xcode.

structure like this:

├── Sources
│   └──App
│   │   └── Controllers
│   │   └── Models
│   │   │   └── File.swift
│   └──Run
│       └── main.swift
└── Package.swift

with main.swift

let config = try Config()
try config.setup()
let drop = try Droplet(config)
try drop.setup()
File.test()
try drop.run()

with File.swift

class File {

    class func test() -> Void{
        print("--\(self)--");
    }
}

the above code xcode can run normally. but using the command swift build to get an error.

log:

Compile Swift Module 'App' (6 sources)
Compile Swift Module 'Run' (1 sources)
/Users/xxx/Documents/testServer/Sources/Run/main.swift:25:1: error: use of 
unresolved identifier 'File'
File.test()
^~~~
CoreServices.cFile:1:12: note: did you mean 'cFile'?
public var cFile: OSType { get }
           ^
<unknown>:0: error: build had 1 command failures
error: exit(1):  /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/xxx/Documents/testServer/.build/debug.yamlhere
2

There are 2 answers

1
Raul Marques On

Probably what is happening is that your class File is in the target 'App', while your Main is in target 'Run', so one can't see the other.

What you need to do is to add the line File.test() into Droplet+setup.swift file over setup() function, that you might have in your project located over the 'App' target.

Some thing like this:

@_exported import Vapor

extension Droplet {
    public func setup() throws {
        try setupRoutes()
        // ADD YOUR CLASS CALL OVER HERE
        File.test()

    }

}
7
Vadim Eisenberg On

Your main.swift is in module Run, while File is in module App. To call a method of a class from another module, you have to perform the following:

  1. Make the class (File) public
  2. Make the method (test) public
  3. Import the module in the file of the calling method - add import App to main.swift