Swift Package top level file

Hi,

Overview

I have a swift package called Vehicles

This contains the following files / types:

  • Car.swift
  • Bus.swift
  • Truck.swift

Doubt

There is a file called Vehicles.swift created, I am not sure what to write there.
If I delete the file it throws the compilation error.

Questions

  1. What should I do in Vehicles.swift? (I don't have any type called Vehicles to define there)
  2. Is it ok to leave it blank?
  3. What is the normal practice in such cases?

Thanks

You will find the SwiftPM documentation very useful.

However, to directly answer your question:

Packages have a manifest file (Package.swift) at the top of the package. This file lists what Products the package offers to other Swift code. If you made the package in the default way (either via the New > Package… menu item in Xcode, or via swift package init in the terminal then your package will have a predefined single Library product whose name matches the name of the Package (in your case Vehicles.) In order to build that product, SwiftPM has a build target (also named Vehicles.)

So, your package already offers a Swift Library named Vehicles and that library is built by SwiftPM using the Vehicles.swift source file. Thus removing that file causes an error.

I would say that it's fine to leave Vehicles.swift empty and define all your library's types in other source files in the /Sources/Vehicles/ folder (source files in this folder will be compiled into the Vehicles Library module.) How you organise the source code in this folder is up to you.

1 Like

@Diggory Thank you so much for that clear explanation.

I will also go through the SwiftPM documentation.

1 Like

Just to be clear, SwiftPM definitely does not require to have a source file with the same basename as the target/directory name.

If you don’t want/need the file Vehicles.swift, it's absolutely fine to delete it.

The only requirement is that every target (except system or executable targets, I believe) must have at least one source file. So you will get an error if you create a new package and then delete the lone Vehicle.swift from the Vehicles target. But that error will go away as soon as you create one or more other .swift files in that directory, as it seems you have done @somu. (Note that SwiftPM expects the source files to be in the target's directory, e.g. under Sources/Vehicles. It's not clear from your original post if you have put them there.)

@somu Please provide more information about your package so we can help you:

  • What's the full directory structure of your package?
  • What compilation error (exact error message) are you seeing?
1 Like

Oops, you are right. Sorry about that.

2 Likes

Thanks a lot @ole!!

You are right, it compiles just fine as long as there are other swift files.

I am so sorry for the confusion.

1 Like

No problem! I'm glad it's now working for you.

1 Like