I am in the process of learning Swift 5 and what better way to write some exercises. But this is becoming a bit of a headache for me. This is what I am trying to do.
I want to write a simple CLI application, but I also want to include unit tests. Let´s say the app is called simple_app
So I went ahead, opened XCode v12.4 and click in New Project. I chose Console Application for MacOS using Swift language. That gives me a folder called simple_app
that contains an .xcodeproj and another folder again with the simple_app
name. Inside that second folder is the actual source code.
It seems Swift project use the convention to look for a main.swift
file as the entry point. So far so good. Now let's say I have something as simple as this:
func add(_ numA:Int, _ numB:Int) -> Int {
return numA + numB
}
func main() {
print(add(4, 5))
}
main()
This works as expected.
So now, I want to add unit tests. After some reading it seems I need to add a new target.I went ahead and used Xcode to create a new target which I called simple_app_tests
. This created some nice templates. But when I try to import the simple_app
mmm target? package? (not sure what that is now) it won't compile anymore.
Some further reading ahead I found out that I cannot link a main.swift file to the test target. That kind of makes sense. It would have 2 entry points: the one for testing, and my main file.
So more reading. And this is where I kind of got stuck.
It seems I need to split my application into a library/package which is independent of the main executable AND then another artifact that contains the main.swift file. Adding a Package through Xcode create another target with its own tests. So I end up with 3 artifacts(not sure what they are actually): simple_app
, simple_app_tests
and simple_app_package
which also contains more targets.... And here is where things are getting too complicated for such a simple app.
Most tutorials/books and stackoverflow questions are more related to IOS development and those solutions for some reason haven't work for my case or are not clear to me. I keep getting linking errors or I end up with a bloated project for such a simple app.
So my question is. Is there a way to structure simple_app
so I am able to write both tests and functionality without over-complicating the structure of y project?
Note: I know that sometime it is ok to split your code into libraries and executable (Rust needs that kind of split) to be able to compile and run tests. Just need some guidance on how it is correctly done on swift. Thanks.