swift 对于包包含了比较严格的访问控制,套路上与rust 比较类似,一般开发的项目都是自己项目的代码,以及引用别人开发
好的包,但是很多时候可能会有自己开发包共享别人的场景
简单包
可以直接使用swift 的cli 创建,或者手工
- 代码结构
├── Package.swift
└── Sources
└── Platform
└── Login.swift
- 代码
Package.swift
// swift-tools-version:5.9
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(name: "MyPackage", targets: ["MyPackage"]),
],
targets: [
.target(
name: "MyPackage"),
]
)
Login.swift
注意需要添加访问控制以及添加public 的init 函数
public struct Login {
var version:String = "v2"
public init(){}
public func login() {
print("Login")
}
}
使用包
- 引用
直接通过path 模式,swift 对于包的引用包含了基于git,以及本地path 模式
import PackageDescription
let package = Package(
name: "myappv3",
dependencies: [
.package(name: "MyPackage", path: "file:///Users/dalong/myios/mypackage"),
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "myappv3",
dependencies: ["MyPackage"]),
]
)
- 使用
import MyPackage;
@main
struct App {
static func main(){
let login = Login()
login.login()
}
}
- 效果
说明
vapor 这个项目包含了不少swift 包,可以学习参考
参考资料
https://www.swift.org/package-manager/
https://github.com/vapor
https://github.com/apple/swift-package-manager
https://swiftpackageregistry.com/
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/accesscontrol
https://medium.com/geekculture/the-best-registries-for-your-swift-package-82c08dd45b05