You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C SPM库DocC文档生成:Xcode正常但命令行报错

问题:Swift Package命令行生成DocC文档失败,但Xcode可正常生成

我正在开发一款可通过Swift Package Manager获取的Objective-C库Sentry,尝试用DocC生成API文档时,执行命令行指令出现错误:

error: target 'Sentry' is not a Swift source module

但在Xcode中通过「Product -> Build Documentation」却能正常生成文档。使用的命令行指令如下:

swift package \
  generate-documentation \
  --allow-writing-to-directory ./docs \
  --target Sentry \
  --output-path ./docs \
  --transform-for-static-hosting \
  --hosting-base-path Sentry

相关Package.swift文件对应Sentry Cocoa仓库的主分支配置。


原因分析

Xcode和swift package命令行工具对Objective-C模块的DocC支持存在核心差异:

  • Xcode内置的文档生成流程针对Objective-C/C模块做了特殊适配,能直接解析头文件中的注释并生成文档。
  • 而swift-docc-plugin(即swift package generate-documentation背后的工具)当前仅原生支持Swift模块,没有为纯Objective-C模块提供内置处理逻辑,因此会抛出“不是Swift源模块”的错误。

解决办法

方案1:添加Swift桥接模块

在Package.swift中新增一个Swift目标作为Objective-C模块的桥接层,让swift-docc-plugin能识别并生成文档:

targets: [
    .target(
        name: "Sentry",
        dependencies: [],
        path: "Sources/Sentry"
    ),
    .target(
        name: "SentrySwift",
        dependencies: ["Sentry"],
        path: "Sources/SentrySwift",
        swiftSettings: [.define("DOCUMENTATION_BUILD")]
    )
]

在这个Swift模块中导入Objective-C头文件,为需要展示的类/方法添加@objc标记和DocC注释,之后命令行指定该Swift目标生成文档:

swift package generate-documentation --target SentrySwift \
  --allow-writing-to-directory ./docs \
  --output-path ./docs \
  --transform-for-static-hosting \
  --hosting-base-path Sentry

方案2:调用Xcode命令行工具生成

直接使用Xcode的xcodebuild docbuild命令模拟Xcode的Build Documentation流程,再转为静态网页:

# 生成doccarchive格式文档
xcodebuild docbuild \
  -scheme Sentry-Package \
  -destination 'platform=iOS Simulator,name=iPhone 15' \
  -derivedDataPath ./build \
  -allowProvisioningUpdates

# 转换为静态可托管的文档
xcrun docc process-archive transform-for-static-hosting \
  ./build/Build/Products/Debug-iphonesimulator/Sentry.doccarchive \
  --output-path ./docs \
  --hosting-base-path Sentry

内容的提问来源于stack exchange,提问作者Kevin Renskers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:30:38