TheNumberDevil TheNumberDevil - 12 days ago 7x
Swift Question

Swift save files to project folder

I'm writing a swift terminal program (let's say it's called "myProject") that requires me to save some files. I would like the files to be saved within the project folder programmatically.

I've seen in this post there are some environment variables like $(PROJECT_DIR) that give the path to the project folder. I've already checked that XCode does have the $(PROJECT_DIR) variable using:

$ xcodebuild -project myProject.xcodeproj -target "myProject" -showBuildSettings

But I'm not exactly sure how I can use this variable in my actual code.
Like if I tried


I would just get the errors:

use of unresolved identifier '$'
use of unresolved identifier 'PROJECT_DIR'

How do I get the path to my project folder programmatically?


Those aren't environment variables that are available to your program at runtime; they're used internally by Xcode for the build process.

Your program is located at Bundle.main.executableURL (NSBundle.mainBundle().executableURL in Swift 2) at runtime (executablePath is also available if you prefer).

If you have additional files that your program needs to access, they must be in a known location. You can use a standard directory in the filesystem such as /usr/local/bin, or you can create a bundle and copy those resources into the bundle as part of the build process.