使用 String(localized:)、String Catalog (.xcstrings) 和类型安全本地化模式, 实现 Swift/SwiftUI 应用国际化的最佳实践。适用于实现多语言支持、添加新 UI 字符串、 或重构 Swift 应用中的硬编码文本。
Ships in game-dev-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
基于 Apple 现代框架和类型安全模式,在 Swift 和 SwiftUI 应用中实现本地化的完整指南。
所有用户可见的文本都必须本地化,包括:
错误:
Text("添加体重")
Button("保存") { ... }
.alert("错误", message: "出了点问题")
正确:
Text(TK.App.Label.addWeight)
Button(TK.App.Action.save) { ... }
.alert(TK.App.Message.errorTitle, message: TK.App.Message.genericError)
通过 TK.App 命名空间的扩展结构,获得编译时安全保证。
每个变量前必须有 /// 文档注释,格式为 /// "<defaultValue>" - <comment>:
/// "Save" - Use for primary save action
public static var save: String {
String(localized: "TK.App.Action.save", defaultValue: "Save", bundle: .main, comment: "Use for primary save action")
}
使用 String(localized:defaultValue:bundle:comment:) 初始化器:
public static var settings: String {
String(
localized: "TK.App.Label.settings",
defaultValue: "Settings",
bundle: .main,
comment: "Settings screen title"
)
}
bundle 参数根据使用场景选择:
.main.module按功能或页面创建扩展:
import SwiftLocale_Core
/// Non-interactive text that describes or labels UI elements
extension TK.App.Label {
/// "Dashboard" - Dashboard screen title
public static var dashboardTitle: String {
String(
localized: "TK.App.Label.dashboardTitle",
defaultValue: "Dashboard",
bundle: .main,
comment: "Dashboard screen title"
)
}
/// "Settings" - Settings screen title
public static var settingsTitle: String {
String(
localized: "TK.App.Label.settingsTitle",
defaultValue: "Settings",
bundle: .main,
comment: "Settings screen title"
)
}
/// "Theme" - Theme selection title
public static var themeTitle: String {
String(
localized: "TK.App.Label.themeTitle",
defaultValue: "Theme",
bundle: .main,
comment: "Theme selection title"
)
}
}
import SwiftLocale_Core
/// Interactive UI elements that trigger actions when tapped
extension TK.App.Action {
/// "Save" - Use for primary save action
public static var save: String {
String(localized: "TK.App.Action.save", defaultValue: "Save", bundle: .main, comment: "Use for primary save action")
}
/// "Cancel" - Use for cancel action
public static var cancel: String {
String(localized: "TK.App.Action.cancel", defaultValue: "Cancel", bundle: .main, comment: "Use for cancel action")
}
}
使用点分隔的命名空间,与代码结构保持一致:
{feature}.{component}.{element}.{property}TK.App.Label.dashboard.currentWeight - 简单值TK.App.Action.common.button.save - 可复用按钮TK.App.Label.settings.personalization.theme.title - 嵌套区块标题TK.App.Message.addEntry.error.invalidWeight - 错误消息对于包含动态内容的字符串,使用返回 String 的函数:
/// Full sentences used for user communication
extension TK.App.Message {
/// "Latest: %@" - Latest entry time
public static func latestEntry(_ time: String) -> String {
String(
localized: "TK.App.Message.latestEntry",
defaultValue: "Latest: \(time)",
bundle: .main,
comment: "Latest entry time"
)
}
/// "Average of %lld entries" - Average of entries count
public static func averageEntries(_ count: Int) -> String {
String(
localized: "TK.App.Message.averageEntries",
defaultValue: "Average of \(count) entries",
bundle: .main,
comment: "Average of entries count"
)
}
}
struct DashboardView: View {
var body: some View {
NavigationStack {
VStack {
Text(TK.App.Label.dashboardTitle)
Button(TK.App.Action.save) {
save()
}
}
.navigationTitle(TK.App.Label.dashboardTitle)
}
}
}
字符串拼接或插值场景:
TextField(TK.App.Placeholder.weightPlaceholder, text: $weightText)
.accessibilityLabel(TK.App.Label.weightValue)
.accessibilityHint(TK.App.Message.weightValueHint(unitSymbol))
始终单独定义无障碍字符串:
extension TK.App.Label {
/// "Add weight entry" - Accessibility label for add button
public static var addWeightEntry: String {
String(
localized: "TK.App.Label.addWeightEntry",
defaultValue: "Add weight entry",
bundle: .main,
comment: "Accessibility label for add button"
)
}
}
extension TK.App.Message {
/// "Opens form to log a new weight" - Accessibility hint for add button
public static var addWeightEntryHint: String {
String(
localized: "TK.App.Message.addWeightEntryHint",
defaultValue: "Opens form to log a new weight",
bundle: .main,
comment: "Accessibility hint for add button"
)
}
/// "Enter your current weight in %@" - Accessibility hint with unit
public static func weightValueHint(_ unitSymbol: String) -> String {
String(
localized: "TK.App.Message.weightValueHint",
defaultValue: "Enter your current weight in \(unitSymbol)",
bundle: .main,
comment: "Accessibility hint with unit"
)
}
}
使用:
Button {
showAddEntry = true
} label: {
Image(systemName: "plus")
}
.accessibilityLabel(TK.App.Label.addWeightEntry)
.accessibilityHint(TK.App.Message.addWeightEntryHint)
现代 Swift 项目使用 .xcstrings 文件(String Catalog)替代 .strings 文件。使用 String(localized:) 时,Xcode 会自动生成条目。
位置:LocaleKit/Localizable.xcstrings
示例结构:
{
"sourceLanguage" : "en",
"strings" : {
"TK.App.Action.save" : {
"comment" : "Use for primary save action",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Save"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "保存"
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
"value" : "保存"
}
}
}
}
},
"version" : "1.0"
}
String(localized:) 条目后构建项目 - Xcode 会自动检测Localizable.xcstringsnew、translated、needs_review+.xcstrings 文件extension TK.App.Label {
/// "On" - iCloud sync enabled state
public static var iCloudSyncEnabled: String {
String(localized: "TK.App.Label.iCloudSyncEnabled", defaultValue: "On", bundle: .main, comment: "iCloud sync enabled state")
}
/// "Off" - iCloud sync disabled state
public static var iCloudSyncDisabled: String {
String(localized: "TK.App.Label.iCloudSyncDisabled", defaultValue: "Off", bundle: .main, comment: "iCloud sync disabled state")
}
}
// 使用
Text(isEnabled ? TK.App.Label.iCloudSyncEnabled : TK.App.Label.iCloudSyncDisabled)
extension TK.App.Message {
/// "Please enter a valid weight" - Invalid weight error
public static var errorInvalidWeight: String {
String(
localized: "TK.App.Message.errorInvalidWeight",
defaultValue: "Please enter a valid weight",
bundle: .main,
comment: "Invalid weight error"
)
}
/// "Failed to save entry: %@" - Save failure error with detail
public static func errorSaveFailure(_ message: String) -> String {
String(
localized: "TK.App.Message.errorSaveFailure",
defaultValue: "Failed to save entry: \(message)",
bundle: .main,
comment: "Save failure error with detail"
)
}
}
// 使用
.alert(TK.App.Message.errorTitle, isPresented: $showingError) {
Button(TK.App.Action.ok) { showingError = false }
} message: {
Text(TK.App.Message.errorInvalidWeight)
}
对于依赖数量的字符串,使用字符串插值:
/// "%lld days" - Days count
public static func days(_ count: Int) -> String {
String(
localized: "TK.App.Message.days",
defaultValue: "\(count) days",
bundle: .main,
comment: "Days count"
)
}
在 .xcstrings 中添加复数规则:
"TK.App.Message.days" : {
"localizations" : {
"en" : {
"variations" : {
"plural" : {
"one" : {
"stringUnit" : {
"state" : "translated",
"value" : "%lld day"
}
},
"other" : {
"stringUnit" : {
"state" : "translated",
"value" : "%lld days"
}
}
}
}
}
}
}
让 Foundation 处理日期本地化:
// 正确 - 遵循用户的 locale
Text(date, style: .date)
Text(date, format: .dateTime.day().month().year())
// 避免 - 硬编码格式
Text(dateFormatter.string(from: date))
审查硬编码字符串:
# 查找潜在的硬编码用户可见字符串
grep -r 'Text("' --include="*.swift" .
grep -r 'Button("' --include="*.swift" .
grep -r '.alert("' --include="*.swift" .
创建 TK.App 条目:
/// 文档注释在视图中替换:
// 之前
Text("当前体重")
// 之后
Text(TK.App.Label.currentWeight)
构建并验证:
.xcstrings 条目如果从 NSLocalizedString 迁移:
// 旧模式
NSLocalizedString("key", comment: "描述")
// 新模式
String(localized: "key", defaultValue: "默认值", bundle: .main, comment: "描述")
两者都兼容 .xcstrings,但 String(localized:) 更推荐使用。
测试字符串长度和布局问题:
// 单元测试:确保视图中没有硬编码字符串
func testNoHardcodedStrings() {
let source = try! String(contentsOfFile: "DashboardView.swift")
let pattern = #"Text\("[^L]"#
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: source, range: NSRange(source.startIndex..., in: source))
XCTAssertEqual(matches.count, 0, "Found hardcoded Text strings")
}
推荐:
String(localized:defaultValue:bundle:comment:) 实现类型安全/// "<defaultValue>" - <comment> 文档注释bundle 参数根据目标类型选择 .main 或 .module禁止:
default: 插值标签在 String(localized:) 中不可用String(localized:defaultValue:) 的 defaultValue 类型为 String.LocalizationValue,仅支持 specifier: 标签,不支持 default: 标签。default: 仅在 SwiftUI Text 的 LocalizedStringKey 插值中有效。
// 错误:String.LocalizationValue 不支持 default: 标签
// 编译错误:Incorrect argument label in call (have '_:default:', expected '_:specifier:')
String(localized: "key", defaultValue: "value \(x, default: "12")")
// 正确:直接使用插值
String(localized: "key", defaultValue: "value \(x)")
// default: 仅在 SwiftUI Text 中有效
Text("value \(x, default: "12")") // 这是 LocalizedStringKey,支持 default:
String(format:) 应替换为 String(localized:)String(format:) 不走本地化系统,应迁移到 String(localized:) 参数化方法:
// 错误:不经过本地化系统
Text(String(format: "姓名:%@ 年龄:%d", name, age))
// 正确:使用 String(localized:) 参数化方法
Text(TK.App.Message.nameAndAge(name, age))
Any / Bool 等类型不能直接用于本地化插值String.LocalizationValue 内置支持 String、Int、Double 等类型的插值,但 Any 和 Bool 类型会产生 deprecation 警告。需要使用 String(describing:) 显式转换。
// 警告:Localized string interpolation produces an unlocalized, debug description for this type of value
defaultValue: "test format: \(value)" // value: Any
defaultValue: "test Bool = \(boolValue)" // boolValue: Bool
// 正确:使用 String(describing:) 显式转换
defaultValue: "test format: \(String(describing: value))"
defaultValue: "test Bool = \(String(describing: boolValue))"
# 导出用于翻译
xcodebuild -exportLocalizations -project MyApp.xcodeproj -localizationPath ./Localizations
# 导入翻译
xcodebuild -importLocalizations -project MyApp.xcodeproj -localizationPath ./Localizations/zh-Hans.xcloc
| 任务 | 模式 |
|---|---|
| 简单字符串 | public static var title: String { String(localized: "TK.App.Label.title", defaultValue: "Title", bundle: .main, comment: "...") } |
| 参数化 | public static func greeting(_ name: String) -> String { String(localized: "...", defaultValue: "Hello, \(name)!", bundle: .main, comment: "...") } |
| 在 SwiftUI 中 | Text(TK.App.Label.featureTitle) |
| 导航标题 | .navigationTitle(TK.App.Label.featureTitle) |
| 无障碍 | .accessibilityLabel(TK.App.Label.accessibilityLabel) |
| 弹窗标题 | .alert(TK.App.Message.errorTitle, message: ...) |
本指南提供了 Swift 本地化的通用最佳实践。请根据项目的具体架构和需求进行调整。
What SKILL.md sets; muted values are Claude Code's defaults
/hocgin-game-dev-skills:swift-localizationfrom game-dev-skills
Claude Code refuses to install this plugin
Claude Code refuses to add this marketplace: The name 'agent-skills' is reserved for official Anthropic marketplaces and can only be used with GitHub sources from the 'anthropics' organization.
Claude Code refuses to add this marketplace: The name 'agent-skills' is reserved for official Anthropic marketplaces and can only be used with GitHub sources from the 'anthropics' organization.
Checked against Claude Code 2.1.332's install rules. The listing below is what the repository ships; Claude Code cannot install it as published.
38 skills in this plugin
/appicon-design从一张或多张 App Icon 案例图中提取设计语言(配色角色、造型语言、材质、光影、质感、细节密度),剥离参考图自身的主体 / 角色 / 布局等 IP,保存为可命名、可复用的「风格主题模板」(设计 DNA + 多版式变体 + 参考 IP 排除),再根据项目名称、类型与核心功能,按指定风格或自动匹配风格,生成原创、不撞脸参考图、符合 iOS App Icon 规范、可直接用于 GPT-Image / Midjourney / SD 等模型的完整提示词(主体描述 + 风格约束 + 版式 + 原创性约束 + 负面约束)。当用户需要设计 App 图标、iOS/macOS 应用图标、备用图标(Alternate App Icon),或想把案例图片沉淀为新的 App Icon 风格时使用。/apple-itunes-apiApple iTunes Search API 完整参考指南。用于搜索 iTunes/Apple Music 目录中的音乐、电影、播客、应用、图书等内容。
触发条件: 用户提及 "iTunes API"、"Apple Music API"、"搜索歌曲"、"查找专辑"、"获取歌词"、
"搜索 App"、"查找播客"、"iTunes 搜索"、"获取封面"、"album art"、"track lookup" 等。
涵盖 Search API、Lookup API、Genre API、RSS Feed Generator 四大端点。
/appstore-product-descriptionOther plugins' skills for the same job