Swift Formatstyle

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

Formats and parses locale-aware numbers, decimals, currencies, percentages, dates, durations, measurements, names, lists, byte counts, and URLs with Foundation FormatStyle and ParseableFormatStyle. Use when replacing legacy Formatter subclasses, designing reusable format APIs, using SwiftUI Text(_:format:), correcting availability, or testing user-facing formatted output across locales.

AI 產生的概覽

指導 Swift 開發者使用 Foundation FormatStyle 與 ParseableFormatStyle 進行地區感知的顯示與解析。

功能
此技能提供在 Swift 中格式化與解析地區感知值的說明與配方,涵蓋數字、小數、貨幣、百分比、日期、時長、度量、姓名、清單、位元組數與 URL。內容包括選擇內建樣式、可用性閘控、SwiftUI Text(_:format:) 整合、自訂 FormatStyle 建立、常見錯誤與審查清單。它產出的是指引與程式碼模式,而非可執行輸出。
適用情境
適用於取代舊版 Formatter 子類別、設計可重複使用的格式 API、在 SwiftUI 中整合格式化值、修正 iOS 16+ 或 iOS 18+ API 的可用性,或跨地區測試面向使用者的格式化輸出。
執行需求
除代理外無需指令碼或執行階段相依性;它引用 Foundation 與 SwiftUI API,並包含一份詳細配方的參考文件。

Swift FormatStyle

Use Foundation's type-safe FormatStyle APIs for user-facing display and ParseableFormatStyle when the same convention must accept input. Route String Catalogs, plurals, localized copy, bundles, and RTL layout to ios-localization; formatting still requires locale review even when no text is translated.

Contents

Workflow

  1. Identify the value's semantic type and whether output is display-only or must round-trip through parsing.
  2. Select the narrowest built-in style and keep the user's current locale unless a wire format explicitly requires another locale.
  3. Render the exact UI with representative locales such as en_US, de_DE, ar_SA, and ja_JP.
  4. Check separators, numbering systems, calendars, currency and unit conventions, text direction, and layout.
  5. If output or parsing fails, fix the style or surrounding copy, restore the input fixture, and rerun the same locale matrix.

Load FormatStyle Recipes [blocked] when implementation needs concrete modifiers, date intervals, relative dates, duration patterns, measurements, names, lists, byte counts, or URL component controls.

Quick Reference

ValueDefault styleImportant constraint
Int, Double.numberConfigure precision, rounding, grouping, notation, or sign only as required.
Decimal.number, .percent, .currency(code:)Prefer for exact decimal display and parsing.
Currency.currency(code:)Pass an ISO 4217 code; never hardcode a symbol.
Percent.percentConfirm whether the input is a fraction (0.85) or whole percent (85).
Date.dateTime, .relative, .intervalRelative output should usually stand alone, not be embedded in a sentence.
Duration.time(pattern:), .units(allowed:width:)Requires iOS 16+; choose compact clock output versus labeled units.
Measurement.measurement(width:usage:)usage: controls locale-aware conversion policy.
PersonNameComponents.name(style:)Do not manually concatenate name parts.
Collections.list(type:width:)Let locale rules choose separators and conjunctions.
Byte count.byteCount(style:)Choose file, memory, decimal, or binary semantics deliberately.
URL.urlRequires iOS 16+; query, port, and fragment are opt-in display components.

Selection and Availability

  • Prefer FormatStyle over legacy NumberFormatter, DateFormatter, DateComponentsFormatter, and manual interpolation for new iOS 15+ code.
  • Duration format styles and URL.FormatStyle require iOS 16+.
  • Date.AnchoredRelativeFormatStyle requires iOS 18+ and formats relative to a fixed anchor rather than the current moment.
  • Omit .locale(...) for normal UI so the style inherits the user's locale. Use a fixed locale only for an explicit protocol or test fixture.
  • Treat relative date output as standalone text unless the entire sentence is localized around it.

Docs: FormatStyle

Parsing

Use the matching parseable style when users edit or import formatted values:

swift
let style = Decimal.FormatStyle.Currency(code: "USD")    .locale(Locale(identifier: "en_US"))
let value = try Decimal("$3,500.63", format: style)let display = value.formatted(style)

The fixed locale above is appropriate only because the input contract is explicitly en_US. For normal UI input, use the user's locale and test round trips with representative decimal separators, currency placement, calendars, and numbering systems.

SwiftUI Integration

Prefer Text(_:format:) so SwiftUI owns the formatted value:

swift
Text(price, format: .currency(code: currencyCode))Text(date, format: .dateTime.month().day().year())Text(duration, format: .units(allowed: [.minutes, .seconds]))

For every user-facing formatted Text, preview or test the exact screen across the locale matrix. Use Text(.now, style: .timer), Text(.now, style: .relative), or Text(timerInterval:) for live-updating time displays rather than manually scheduling string refreshes.

Custom FormatStyle

Create a custom style only when built-in composition cannot express the domain convention. FormatStyle refines Codable and Hashable; keep styles as reusable values and add ParseableFormatStyle only when input must round-trip.

swift
struct AbbreviatedCountStyle: FormatStyle {    func format(_ value: Int) -> String {        switch value {        case ..<1_000: "\(value)"        case 1_000..<1_000_000: String(format: "%.1fK", Double(value) / 1_000)        default: String(format: "%.1fM", Double(value) / 1_000_000)        }    }}
extension FormatStyle where Self == AbbreviatedCountStyle {    static var abbreviatedCount: Self { .init() }}

Custom styles still need locale and accessibility review; a compact English suffix may not be suitable for every locale.

Common Mistakes

MistakeFix
Manual formatting or legacy formatter allocation in view codeUse the matching FormatStyle and Text(_:format:).
Hardcoded currency symbol or localePass an ISO currency code and inherit the user locale unless the contract says otherwise.
Binary floating-point for exact decimal inputUse Decimal.FormatStyle and its matching parse strategy.
Assuming URL.formatted() preserves every componentOpt in to .port(.always), .query(.always), or .fragment(.always) only when those components should display.
Relative date output embedded in a larger sentenceKeep it standalone or localize the complete sentence.
Clock-style duration used for proseUse .units(allowed:width:) for labeled output.
Measurement conversion left implicitSelect a usage: appropriate to the UI.
One-locale spot checkRun the same exact-screen fixture across representative locales and fix/rerun failures.

Review Checklist

  • Semantic value type and display-versus-parse requirement identified
  • Built-in FormatStyle used where it can express the convention
  • Availability gated beside iOS 16+ and iOS 18+ APIs
  • Currency uses an ISO 4217 code; exact decimal values use Decimal
  • User locale inherited unless a protocol explicitly fixes it
  • Relative date text stands alone or the full sentence is localized
  • URL components and measurement usage: are deliberate
  • SwiftUI uses Text(_:format:) for formatted values
  • Exact rendered UI and parse round trips pass the representative-locale matrix

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/swift-formatstyle提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新