官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 耒阳市| 小金县| 济宁市| 绿春县| 南投市| 日喀则市| 措勤县| 石城县| 扶风县| 甘南县| 海南省| 怀仁县| 浦北县| 临洮县| 饶阳县| 太湖县| 彝良县| 长顺县| 手游| 延安市| 宜良县| 原平市| 永泰县| 休宁县| 望奎县| 七台河市| 左权县| 高尔夫| 兴海县| 特克斯县| 都兰县| 宣汉县| 黔东| 吴旗县| 游戏| 宜川县| 封丘县| 兰西县| 易门县| 宁安市| 呼和浩特市|