Hands-On Full:Stack Development with Swift
上QQ阅读APP看书,第一时间看更新

Consuming a Swift package

Next, we will try to use this package to create an executable package called cat that concatenates and prints the contents of the files passed in as arguments to the command. This executable will work like the built-in-system cat command found in most Unix based operating systems. To do so, we need to perform the following steps:

  1. Open the Terminal and create a directory called cat (mkdir cat) and change the directory into it (cd cat).
  2. Initialize the package by running swift package init --type executable. This will generate a main.swift, which is the entry point for the executable and the code will start executing line by line starting from that file.
  3. Add the URL to your GitHub repo that contains the FileReader package and add the following line in your Package.swift under dependencies:
.package(url: "https://github.com/<repoaccount>/<reponame>", from: "1.0.0"),
  1. Add your FileReader package to the dependencies under the targets section in Package.swift:
import PackageDescription

let package = Package(
name: "cat",
dependencies: [
.package(url: "https://github.com/ankurp/FileReader", from: "1.0.0"),
],
targets: [
.target(
name: "cat",
dependencies: ["FileReader"]),
]
)
  1. Add the following code to main.swift:
import FileReader

for argument in CommandLine.arguments {
guard argument != "arg1" else { continue }

if let fileContents = FileReader.read(fileName: argument) {
print(fileContents)
}
}

Let's try to understand what we have done in the preceding code:

  1. Import the FileReader package:
import FileReader
  1. Iterate over the command-line arguments:
for argument in CommandLine.arguments {
  1. We ignore the first argument using the guard clause in Swift because it is the command name cat:
guard argument != "arg1" else { continue }
  1. Print the contents of the file by printing it in the console:
if let fileContents = FileReader.read(fileName: argument) {
print(fileContents)
}

Now that we have understood the code, let's build and run it to see whether it works. To build and run, just type the following command in the Terminal:

$ swift run cat Package.swift Sources/cat/main.swift

You should see the contents of both the files, Package.swift and Sources/cat/main.swift, printed in the console. Great job! We have a working command line tool written in Swift using one of our published Swift packages: