# SwiftLint **Repository Path**: unotseeme/SwiftLint ## Basic Information - **Project Name**: SwiftLint - **Description**: help for swift - **Primary Language**: Swift - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-04-13 - **Last Updated**: 2026-11-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SwiftLint 一个 Swift Package 工具库,收集日常开发可用的扩展与工具:字符串/日期/集合扩展、CoreData 查询与谓词构造、轻量键值存储、表达式求值,以及一套自实现的 DNS 解析能力。 > 与 `realm/SwiftLint`(代码检查工具)无关,本库不提供 lint 规则。 - **零第三方依赖**:仅使用 `Foundation`、`Darwin`、`CoreData`、`CryptoKit`(系统框架) - **平台**:iOS 14+ / macOS 10.15+ / watchOS 7+ / Linux(glibc 发行版;部分 API 因平台框架缺失被裁切,见 [平台能力矩阵](#平台能力矩阵))。其中 `AttributedString` 样式扩展另需 iOS 15 / macOS 12 / watchOS 8 - **Swift**:tools 5.3+(建议 Xcode 14.2 / Swift 5.7;Linux 构建对工具链另有要求,见[已知限制](#已知限制)) > 开发前请先阅读 [AGENTS.md](AGENTS.md):其中记录了本仓库的 AI 协作规范、分支约定、编码与测试要求。 --- ## 集成方式 `Package.swift` 使用了 `.unsafeFlags(["-enable-library-evolution"])`,因此**本包不能作为 SPM 依赖被其他项目引用**(消费方会编译失败)。集成方式: - **本地包**:Xcode → File → Add Package Dependencies… → Add Local…,选择本仓库根目录 - **Xcode 工程**:直接把 `Sources/SwiftLint` 目录加入工程(target membership 按需勾选) 命令行构建与测试: ```bash swift build swift test ``` Linux 上构建时,`Package.swift` 会自动下发 `-no-verify-emitted-module-interface`(用于绕开 `public struct SwiftLint` 与模块同名遮蔽导致的 SwiftPM ≥ 6.0 接口校验失败)。该开关仅在 Linux 构建时生效,Apple 平台不受影响。 --- ## 能力一览 ### String 扩展 ```swift "hello.txt".ends(with: ".txt") // true "a,b,c".replace(search: ",", with: "-") // "a-b-c",正则替换 "a-b-c".replace(search: "-", with: "+", count: 1) // "a+b-c",count 限制替换次数,nil 表示全部替换,0 与负数表示不替换 "a😀b".replace(search: "b", with: "X") // "a😀X",含 emoji 等非 BMP 字符时结果同样正确 "hello".md5() // CryptoKit MD5(仅 Apple 平台可用,见[平台能力矩阵](#平台能力矩阵)) "hello".base64encode() // base64decode() 反向 "hello".urlEncoded() // urlDecoded() 反向 "abc".substr(start: 0, length: 2) // "ab" "\\u4f60\\u597d".unicodeDecode() // unicodeEncode() 反向 "2024-01-02".match(regex: "[0-9]{4}-[0-9]{2}-[0-9]{2}") ``` ### Date 扩展 ```swift Date.from("2024-01-02 03:04:05") // 自动识别常用格式 Date(int: 1_700_000_000) Date().datetimeString // "yyyy-MM-dd HH:mm:ss" Date().year // 2024 Date().weekInt // 周日为 0 Date().days(to: other) // hours/minutes/seconds 同理 Date().lunarDayInt // 农历日 Date().ctDayInt // 干支日 Date().lunarMonths(since: Date()) // 农历月数 ``` ### Array / Dictionary / Set 扩展 ```swift [1, 2, 3, 4].except(elements: [2]) // [1, 3, 4] [1, 2, 3, 4].only(elements: [1, 2]) // [1, 2] [1, 2, 3].sum() // Element: Numeric ["a", "bb"].groupBy { $0.count } // [1: ["a"], 2: ["bb"]] ["a", "a", "b"].uniq { $0 } // ["a", "b"],保留每组首次出现的元素,顺序与输入一致 ["a", "b"].loop { element, next in ... } // 串行迭代,asyncEach 支持首尾回调 ["k": 1].only(keys: ["k"]) // Dictionary 同样有 only/except/add ``` ### 基础类型与 Optional(Lang) ```swift nil.isNil // true opt.with { value in ... } // 有值才执行 5.lpad(3) // "005" 5.hexedString() // "05",宽度不足补 0;负数带负号,如 -1 得到 "-01";不按 32 位截断 3.14159.toString(precision: 2) // "3.14" 3.14159.roundTo(places: 2) Int64(3).date ``` ### Encodable / Decodable ```swift struct User: Codable { let id: Int; let name: String } User(id: 1, name: "a").stringified // 格式化 JSON User.fromJSON(with: jsonString) // 解码,失败返回 nil [String].fromJSON(with: data) ``` ### CoreData:谓词构造与查询 ```swift // 链式构造 NSPredicate let predicate = NSPredicate.build { builder in builder .add("age", operation: .GT, value: 18) .whereIn("city", vars: [.init("Beijing"), .init("Shanghai")]) .whereBetween("score", a: 60, b: 100) .whereNotNull("email") } // 字典条件自动转谓词,支持 >、<、!=、~=(IN)、!~(NOT IN)前缀,比较前前缀会被去掉 NSPredicate(from: ["age": ">18", "city": "~=[\"Beijing\"]"]) // 查询辅助 let users = helper.findBy(request: User.fetchRequest(), conds: ["city": "Beijing"], limit: 10) let user = helper.findById(request: User.fetchRequest(), id: "123") // 上下文操作 context.exec { ctx in ... } // 捕获错误,返回 Bool context.silentSave() ``` `PredicateBuilder` 支持 `IN / NOT IN / BETWEEN / NOT BETWEEN / CONTAINS / NULL / != / == / > / >= / < / <=` 等操作(`LE` 表示「小于等于」,`LT` 表示「小于」),以及 `union()`(`||`)、`whereSub`(子条件)、`pipe` / `with` / `whether` / `map` 等流式辅助。 ### CoreDataHelper 对 `NSPersistentContainer` 的轻封装:读写分离的容器(`persistentContainer` / `reader`)、泛型 `Query` 查询类(`findBy` / `findByOne` / `findById` / `refresh` / `flush` / `delete`)、`instance()` 创建托管对象、`saveContext()` 保存。 ### Util 工具 ```swift // LintData:轻量键值存储,默认落 UserDefaults,可自定义 source LintData().set("k", with: 1) LintData().get("k") data["k"] = 2 // 支持下标读写 // LintExpression:表达式求值,支持中文标点与变量 let exp = LintExpression("(#a# + #b#) * 2", context: ["#a#": 3, "#b#": 4]) exp.double // 14 exp.int // CommonUtil:延时执行与日志 CommonUtil().wait(for: 1) { ... } CommonUtil().i("message") ``` > `LintExpression` 的变量用 `#名字#` 形式引用,`context` 的键也要带 `#`;不带 `#` 的变量按 `0` 取值。 ### DNS 解析 不依赖任何第三方库,iOS / macOS / Linux 通用。 ```swift // 1. 系统默认解析(getaddrinfo),等价于系统 DNS,行为最稳 let addresses = try DNS.resolve(domain: "example.com") // 2. 指定 DNS 服务器:自建 DNS 报文,UDP 53 发送,响应被截断(TC=1)时自动回退 TCP 53 let addresses = try DNS.resolve(domain: "example.com", server: "8.8.8.8") // 服务器地址支持端口与 IPv6:1.1.1.1:5353、[::1]:53 // 3. 需要 TTL 与记录类型时 let records = try DNS.resolveRecords(domain: "example.com", server: "8.8.8.8") for record in records { print(record.name, record.type, record.ttl, record.value) } // 4. 异步调用 DNS.resolve(domain: "example.com", server: "8.8.8.8") { result in switch result { case .success(let addresses): print(addresses) case .failure(let error): print(error) } } ``` 行为约定: - 默认同时查询 A 与 AAAA,自动跟随 CNAME(最多 3 跳),并携带 EDNS0 OPT 记录(UDP 报文上限 4096) - 服务器地址支持 `1.2.3.4`、`1.2.3.4:5353`、`[::1]:53`,端口默认 53 - 错误以 `DNSError` 枚举抛出(超时、域名不存在、响应非法、socket 失败等) - iOS 上若使用**局域网** DNS 服务器,宿主 App 需在 Info.plist 声明 `NSLocalNetworkUsageDescription`;访问公网 DNS 无此限制 ### 富文本样式扩展 按正则或子串定位文本区间,把样式施加到全部命中区间。 ```swift var text = AttributedString("订单 123 已发货,订单 456 待付款") // 多个模式之间是「或」的关系,命中任意一个即施加样式 text.lintApplyStyles(matchingRegex: ["订单 [0-9]+"]) { fragment in fragment.link = URL(string: "https://match.example") } text.lintApplyStyles(matching: ["订单", "待付款"]) { fragment in fragment.link = URL(string: "https://match.example") } ``` --- ## 平台能力矩阵 Linux 已支持(glibc 发行版,Ubuntu 22.04 + Swift 6.0 实测通过),但部分 API 因平台框架缺失被裁切: | 裁切项 | 原因 | | --- | --- | | `String.md5()` | 依赖 CryptoKit,Linux 无对应实现;本包不引入替代依赖以维持零第三方依赖 | | `PredicateBuilder` / `NSPredicate.build` | 依赖 CoreData 生态,且其 format 谓词语法在 swift-corelibs-foundation 支持有限 | | `NSPredicate(from:)` | 同上 | | `CoreDataHelper` | 依赖 `NSPersistentContainer`(CoreData);泛型查询类 `Query` 同在 `CoreDataHelper.swift` 内,一并裁切 | | `NSManagedObjectContext` 扩展(`exec` / `silentSave` / `merge`) | 依赖 CoreData | 上述 API 在 Apple 平台(iOS / macOS / watchOS)上完全不受影响,调用方式与行为保持一致。 `AttributedString` 的样式扩展(`lintApplyStyles(matchingRegex:_:)`、`lintApplyStyles(matching:_:)`)**未被裁切**,在 Apple 平台与 Linux 上行为一致;但 `AttributedString` 在 Apple 平台需要 iOS 15 / macOS 12 / watchOS 8,更低的系统版本没有这个类型,两个方法因此标注了 `@available`。 --- ## 接口文档 仓库提供面向调用者的接口文档,按模块组织,包含每个 `public` API 的完整签名、行为说明与调用范例。 - 文档总入口:[Docs/README.md](Docs/README.md) - 中文文档:[Docs/zh/README.md](Docs/zh/README.md) - English documentation: [Docs/en/README.md](Docs/en/README.md) --- ## 测试 ```bash swift test # 全部用例 swift test --filter DNSMessageTests # 按类过滤 DNS_TEST_SERVER=8.8.8.8 swift test # 打开真实 DNS 链路测试 ``` 测试覆盖报文编解码的字节级断言、压缩指针解析、UDP 查询、TCP 回退、CNAME 跟随、异步回调等;网络类用例均基于本地 mock DNS 服务器,不依赖外网。 跨平台验证: ```bash xcodebuild -scheme SwiftLint -destination 'generic/platform=iOS' build xcodebuild -scheme SwiftLint -destination 'platform=iOS Simulator,name=iPhone 14' test ``` Linux 端到端验证(容器 `swift:6.0-jammy`,Ubuntu 22.04 + Swift 6.0): ```bash docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD":/src -w /src \ swift:6.0-jammy swift test --scratch-path /tmp/sl-linux-build ``` 该命令在仓库根目录执行,要求本机已存在 `swift:6.0-jammy` 镜像(需提前准备,容器内不会联网拉取)。`--scratch-path` 指向仓库外的路径,避免在仓库内生成构建产物;只需编译、不跑测试时,把末尾换成 `swift build --scratch-path /tmp/sl-linux-build`。 容器内执行 `swift build` 与 `swift test`,共 78 个用例。Linux 侧与 Apple 平台的已知差异: - CoreData 相关的 19 个用例在 Linux 上被裁切,不参与执行(97 = 78 + 19) - 真实 DNS 链路测试需通过 `DNS_TEST_SERVER` 指定服务器,未配置时按「跳过」处理 --- ## 已知限制 - `Package.swift` 的 `unsafeFlags` 导致本包无法作为 SPM 依赖被消费,只能本地包或 Xcode 工程集成 - `watchOS` 目标尚未在 CI 环境验证(缺 watchOS SDK 时无法构建) - 编译时存在一条既有告警:`public struct SwiftLint` 与模块 `SwiftLint` 同名遮蔽(SR-14195) - iOS 访问局域网 DNS 服务器需要宿主 App 声明本地网络权限 - Linux 侧构建依赖 `-no-verify-emitted-module-interface` 绕开模块名遮蔽(SR-14195)导致的接口校验失败;该开关仅在 Linux 下发,不影响 Apple 平台 - Linux 构建要求工具链支持 `-no-verify-emitted-module-interface` 选项:并非所有 Swift 版本都提供该选项(实测环境为 Swift 6.0),使用更早的工具链可能出现 unknown argument 一类的构建失败 - Linux 端到端测试依赖 SwiftPM 的自动用例发现,需 SwiftPM 5.4+(Swift 5.4 起默认启用);实测环境为 Ubuntu 22.04 + Swift 6.0 - Linux 上 `DateTests` 等断言已显式指定 `Asia/Shanghai` 时区,不依赖运行环境默认时区 --- ## License 本仓库暂未附带 LICENSE 文件,使用或分发前请与维护者确认授权方式。