← 返回
未分类 中文

I18n Swift

Swift internationalization patterns, String(localized:) usage, and semantic key naming for macOS/iOS apps
Swift国际化模式、String(localized:)用法及macOS/iOS语义键命名
soponcd soponcd 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 368
下载
💾 0
安装
1
版本
#latest

概述

Swift Internationalization

Expert-level Swift i18n patterns for macOS/iOS applications. Covers string localization, semantic key naming, and best practices.

When: to Use

Use this skill when:

  • Adding localized strings to SwiftUI views
  • Creating new localization keys
  • Writing String(localized:) calls
  • Organizing Localizable.strings files
  • Reviewing i18n implementation in Swift projects

Core Principles

1. String(localized:) Pattern

// Always use String(localized:) for user-facing text
Text(String(localized: "common.save"))
Button(String(localized: "sidebar.today"))

// Never hardcode strings
Text("Save")  // ❌ Wrong

2. Semantic Key Naming

Use domain.feature.key pattern:

// Good: Semantic keys
"app.name" = "TimeFlow"
"common.save" = "Save"
"sidebar.today" = "Today"
"settings.theme.title" = "Theme"

// Bad: Non-semantic keys
"saveButton" = "Save"
"viewTitle1" = "Today"
"themeTitle" = "Theme"

3. Localizable.strings Organization

Group by domain with MARK comments:

/*
 Localizable.strings
 TimeFlow
*/

// MARK: - App
"app.name" = "TimeFlow";

// MARK: - Common
"common.delete" = "Delete";
"common.save" = "Save";
"common.cancel" = "Cancel";

// MARK: - Sidebar
"sidebar.today" = "Today";
"sidebar.settings" = "Settings";
"sidebar.daily_note" = "Daily Note";

// MARK: - GTD Navigation
"gtd.inbox" = "Inbox";
"gtd.today" = "Today";
"gtd.projects" = "Projects";

Key Naming Conventions

DomainFeatureExamples
---------------------------
app-app.name
commondelete, save, cancelcommon.delete, common.save
sidebartoday, settings, searchsidebar.today, sidebar.settings
home` today, progress, timelinehome.today, home.progress
gtdinbox, next, projectsgtd.inbox, gtd.next
settingstheme, language, syncsettings.theme.title
syncidle, syncing, failedsync.idle, sync.syncing

SwiftUI Usage Patterns

Text Component

struct TodayView: View {
    var body: some View {
        VStack {
            Text(String(localized: "home.today"))
                .font(.title)

            Text(String(localized: "home.no_events"))
                .foregroundStyle(.secondary)
        }
    }
}

Button with Localized String

Button(String(localized: "common.save")) {
    // Save action
}
.disabled(isSaving)

Navigation Titles

NavigationLink(destination: SettingsView()) {
    Label(String(localized: "sidebar.settings"), systemImage: .gear)
}

Best Practices

PracticeReason
------------------
Use String(localized:)Prevents hardcoding, enables i18n
Semantic key namesSelf-documenting, easier maintenance
Group with // MARK:Organized, searchable strings files
Use domain.feature.keyClear ownership, prevents collisions
Update all languages togetherPrevents missing translations
Avoid format strings in keysUse Swift interpolation instead

String Interpolation

// Good: Use Swift interpolation
let message = String(localized: "sync.completed.count")
    .replacingOccurrences(of: "{count}", with: "\(count)")

// Alternative: Use String(format:) for localized format strings
let formatted = String(
    localized: "sync.completed.count",
    comment: "Number of items synced"
)

// Localizable.strings entry:
// "sync.completed.count" = "Synced %d items";

Common Pitfalls

PitfallConsequencePrevention
----------------------------------
Hardcoded stringsCan't localizeAlways use String(localized:)
Non-semantic keysDifficult to maintainUse domain.feature.key pattern
Missing translationsShows key nameAdd entries to all .strings files
Format strings in keysAmbiguous valuesUse Swift interpolation
Duplicate keysConfusing maintenanceSearch before adding

Testing Patterns

func testLocalizationKeys() {
    // Verify all keys exist in Localizable.strings
    let keys = ["app.name", "common.save", "sidebar.today"]
    for key in keys {
        let localized = String(localized: key)
        XCTAssertNotEqual(localized, key, "Key not found: \(key)")
    }
}

Running Tests

# Test localization
xcodebuild test -scheme YourApp \
  -destination 'platform=macOS' \
  -only-testing:'YourAppTests/LocalizationTests/testKeysExist'

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-31 16:57 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

design-media

Web Design Guidelines

soponcd
审查 UI 代码以确保符合 Web 界面规范,适用于“审查我的 UI”“检查可访问性”“审计设计”“审查 UX”“检查我的网站”等请求。
★ 3 📥 1,333
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 677 📥 327,223
dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 72 📥 181,813