Swift / iOS 开发环境配置 - 码剑客

配置 Swift 与 iOS 开发环境:Xcode 命令行工具、Swift Package Manager、模拟器与设备调试、Linux 工具链与常见报错排查。

Swift 5.10+ / Xcode 15+更新于 2026-10-29共 27 条

安装与版本管理

macOS 安装 Xcode 命令行工具(含 Swift),无需完整 Xcode 也能编译 Swift 包

xcode-select --install
xcodebuild -version
swift --version

开发 iOS 应用仍需从 App Store 安装完整 Xcode 与模拟器

切换当前生效的 Xcode 路径,多版本共存时使用

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

Linux 上安装 Swift 官方工具链所需的系统依赖

# Linux(Ubuntu 22.04 示例)
sudo apt update && sudo apt install -y binutils git gnupg2 libc6-dev libcurl4-openssl-dev libedit2 libgcc-11-dev libpython3-dev libsqlite3-0 libstdc++-11-dev libxml2-dev libz3-dev pkg-config tzdata zlib1g-dev

安装 SwiftLint 与 SwiftFormat,统一代码规范与格式

# macOS
brew install swiftlint swiftformat

用官方 Swiftly 管理多个 Swift 工具链版本(macOS/Linux)

swiftly install latest
swiftly use latest

镜像源与代理

为单个依赖设置镜像地址,适合内网或拉取缓慢的包

swift package config set-mirror --original-url https://github.com/apple/swift-argument-parser --mirror-url https://gitee.com/mirrors/swift-argument-parser

撤销依赖镜像,恢复为原始地址

swift package config unset-mirror --original-url https://github.com/apple/swift-argument-parser

SwiftPM 底层走 git,代理通过 git 全局配置生效

git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890

关闭代理后清理 git 配置,避免 clone 一直超时

git config --global --unset http.proxy
git config --global --unset https.proxy

环境变量

确认当前开发者目录、Swift 版本与模拟器 SDK 版本

xcode-select -p
swift --version
xcrun --sdk iphonesimulator --show-sdk-version

用环境变量固定 Xcode 路径,配合 CI 与多版本切换

echo 'export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer' >> ~/.zshrc

列出可用的模拟器设备与运行状态

xcrun simctl list devices

首次使用 Xcode 时接受许可协议,否则命令行构建会失败

sudo xcodebuild -license accept

创建工程与验证

用 SwiftPM 创建可执行工程并直接运行

mkdir hello && cd hello
swift package init --type executable
swift run

生成优化产物并运行,产物路径随平台不同

swift build -c release
.build/release/hello

运行包内全部 XCTest 测试

swift test

解析依赖并查看依赖树,排查版本冲突

swift package resolve
swift package show-dependencies

启动指定模拟器并打开模拟器窗口

xcrun simctl boot "iPhone 15"
open -a Simulator

编辑器与插件

VS Code 安装官方 Swift 扩展,获得补全、调试与测试支持

code --install-extension swiftlang.swift-vscode

用 Xcode 打开工程;SwiftPM 工程也可直接 open Package.swift

open -a Xcode hello.xcodeproj

命令行在模拟器上跑测试,便于接入 CI

xcodebuild -scheme hello -destination 'platform=iOS Simulator,name=iPhone 15' test

常见问题排查

报 xcrun: error: active developer path 无效时,重置开发者目录

xcode-select -p
sudo xcode-select --reset
高危

模拟器状态异常或数据损坏时清空重建(会删除模拟器内数据)

xcrun simctl erase all
高危

Xcode 构建缓存异常导致奇怪报错时清理派生数据

rm -rf ~/Library/Developer/Xcode/DerivedData

SwiftPM 依赖状态损坏时重置后重新解析

swift package reset
swift package resolve

查看签名信息,排查真机安装失败与证书过期

codesign -dv --verbose=4 /path/to/App.app

目标模拟器系统不存在时,确认已安装对应 runtime

xcrun simctl list runtimes

本网站使用 Cookie 以确保您在我们的网站上获得最佳体验。 隐私政策.