Swift项目的CI/CD:GitHub Actions分步指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么 Swift 项目需要 CI/CD?



iOS 和 macOS 开发需要高度的代码质量和可靠性。每一次更改都可能破坏构建或导致测试回归。手动检查是一个缓慢且不可靠的过程。这时 CI/CD(持续集成/持续交付)就派上了用场。



GitHub Actions 是一个强大且内置的工具,可以直接在您的仓库中自动化工作流程。它允许您在每次推送或创建 Pull Request 时,自动构建项目、运行测试、分析代码,甚至将应用发布到 App Store 或 TestFlight。



在本文中,我们将探讨如何在 GitHub Actions 上为 Swift 项目设置一个完整的 CI/CD 流水线。您将学习如何创建工作流、配置构建、运行测试、代码检查以及部署。所有代码示例均可直接使用。



主体部分



1. 用于 Swift 的 GitHub Actions 基础



GitHub Actions 基于存储在 .github/workflows/ 目录中的 YAML 文件运行。每个文件描述一个或多个工作流。对于 Swift 项目,我们需要一个带有 macOS 的 runner,因为 iOS/macOS 应用的构建只能在该平台上进行。



Swift 项目的基本工作流如下所示:



name: Swift CI

on: push: branches: [ "main" ] pull_request: branches: [ "main" ]

jobs: build-and-test: runs-on: macos-latest

steps: - uses: actions/checkout@v4

- name: Build run: swift build

- name: Run tests run: swift test


让我们分析一下关键点:

  • on — 触发器:在推送到 main 分支或创建 Pull Request 时启动。
  • runs-on: macos-latest — 为 runner 使用最新版本的 macOS。
  • actions/checkout — 用于克隆仓库的标准 action。
  • swift build 和 swift test — Swift Package Manager 的命令。


这个最小的流水线已经提供了基本的检查。但对于真正的 iOS/macOS 应用来说,这还不够——还需要配置 Xcode、模拟器和依赖项。



2. 为 iOS/macOS 应用配置构建和测试



如果您的项目使用 Xcode(例如 .xcworkspace 或 .xcodeproj),则 swift build 命令不适用。相反,我们使用 xcodebuild。还需要指定 scheme 和 destination(例如 iPhone 模拟器)。



iOS 应用的工作流示例:



name: iOS CI

on: push: branches: [ "develop", "main" ] pull_request: branches: [ "develop", "main" ]

jobs: test: runs-on: macos-14

steps: - uses: actions/checkout@v4

- name: Select Xcode version run: sudo xcode-select -s /Applications/Xcode_15.2.app

- name: Install CocoaPods (if using) run: pod install

- name: Build and Test run: | xcodebuild clean test \ -workspace YourApp.xcworkspace \ -scheme "YourApp Scheme" \ -destination 'platform=iOS Simulator,name=iPhone 15,OS=17.2' \ -resultBundlePath TestResults env: DEVELOPER_DIR: /Applications/Xcode_15.2.app/Contents/Developer

- name: Upload test results if: always() uses: actions/upload-artifact@v4 with: name: test-results path: TestResults.xcresult


重要细节:

  • macos-14 — 使用带有 Xcode 15.2 的 macOS 14 Sonoma。
  • xcode-select — 明确指定 Xcode 版本以避免不兼容。
  • resultBundlePath — 将测试结果保存为工件以供进一步分析。

博客

书籍推荐