Swift Package初体验

Swift Package Manager初体验

环境:
macOS Monterey 12.0.1、
Xcode 13.1、
Swift 5.5.1

1. 简介

2. 建立工程

建立一个工程文件夹,然后进入文件夹中,执行 swift package init --type executable
type 有多种类型 empty | library | executable | system-module | manifest (default: library)
不带 --type时,默认为library

➜  swift mkdir GLSqliteOp
➜  swift cd GLSqliteOp 
➜  GLSqliteOp swift package init --type executable
Creating executable package: GLSqliteOp
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/GLSqliteOp/main.swift
Creating Tests/
Creating Tests/GLSqliteOpTests/
Creating Tests/GLSqliteOpTests/GLSqliteOpTests.swift

3. 执行

  1. $ swift run
➜  GLSqliteOp swift run
[3/3] Build complete!
Hello, world!

运行完成之后将会在工程中生成一个.build的文件夹。
里面有着很多执行了的文件,
例如debug文件夹中就有一些编译的文件和一个和项目相关的可执行文件

  1. $ .build/debug/GLSqliteOp

可执行文件是可以直接运行的,和上面swift run之后的结果是一样的

  1. 用xcode 打开Package.swift

此时你会发现这个和xcodeproj这种文件打开后的样式是一样的,层次分明.
点击运行即可 或者使用 Command+R直接运行

4. 添加依赖

本案例中就以fmdb为例
在Package.swift中加入相关依赖语句

.package(
    name: "FMDB",
    url: "https://github.com/ccgus/fmdb",
    from: "2.7.7"),

给对应的Target加入依赖

.executableTarget(
            name: "GLSqliteOp",
            dependencies: ["FMDB"]),

5. 编写实例代码

  • 关联数据库
  • 建立表结构
  • 插入数据
  • 查询数据

关联 例子

6. 打包

$ swift build -c release
如果当前Package中有多个product那需要指定相关的名称
在目录下: .build/release

7. help文档

  • swift package --help
  • swift package init --help
  • swift run --help
  • swift build --help

资料

posted @ 2021-12-01 16:16  古龙•历山大亚  阅读(247)  评论(0编辑  收藏  举报