SuperAPI AI 工具集

swift-formatstyle

通用与其它

查看项目

更新于 10-15 21:12

技能介绍

用途:面向 iOS 15+ 代码,用 Foundation 的 FormatStyle 与 ParseableFormatStyle 做面向用户的本地化格式化与解析,替代 NumberFormatter、DateFormatter、DateComponentsFormatter 和手工字符串拼接。

主要能力:覆盖 Int/Double 的 .number、Decimal 的 .number/.percent/.currency(code:)、货币、百分比、日期(.dateTime、.relative、.interval)、时长(.time(pattern:)、.units(allowed:width:))、度量(.measurement(width:usage:))、PersonNameComponents 的 .name(style:)、集合的 .list(type:width:)、字节数 .byteCount(style:) 与 URL 的 .url。

使用方式:先判断值的语义类型及是否需往返解析;选择最窄的内置样式并继承用户当前 locale,除非协议明确要求固定 locale。解析时用匹配的 parseable 样式,例如: 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) SwiftUI 中优先用 Text(_:format:),如 Text(price, format: .currency(code: currencyCode))。

适用场景:需要本地化展示或接受用户输入的数字、货币、日期、时长、度量、姓名、列表、字节数、URL 等界面。

限制:Duration 与 URL.FormatStyle 需 iOS 16+,Date.AnchoredRelativeFormatStyle 需 iOS 18+。货币须传 ISO 4217 代码,精确小数用 Decimal。相对日期通常应独立成句。URL 的 port、query、fragment 需显式开启才显示。自定义 FormatStyle 仍需做 locale 与无障碍审查。格式化即使无文本翻译也需按 en_US、de_DE、ar_SA、ja_JP 等代表性 locale 复核分隔符、数字系统、日历、货币与单位约定、文本方向与布局。