### Install Swift FormatStyle Agent Skill for Gemini Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md Alternative installation method for Gemini using the extensions install command. Consent is required. ```bash gemini extensions install https://github.com/n0an/Swift-FormatStyle-Agent-Skill.git --consent ``` -------------------------------- ### Install Node.js using Homebrew Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md If npx is not found, install Node.js using Homebrew. This is a prerequisite for using npx. ```bash brew install node ``` -------------------------------- ### Install Swift FormatStyle Agent Skill for Claude Code Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md Alternative installation method for Claude Code using the /plugin command. ```bash /plugin install n0an/Swift-FormatStyle-Agent-Skill ``` -------------------------------- ### Install Swift FormatStyle Agent Skill Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md Use npx to add the Swift FormatStyle Agent Skill to your projects. Ensure Node.js is installed. ```bash npx skills add https://github.com/n0an/Swift-FormatStyle-Agent-Skill --skill swift-format-style ``` -------------------------------- ### SwiftUI Text View Formatting Examples Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/swiftui.md Provides examples of using various format styles with the `Text` view in SwiftUI for dates, numbers, and durations. ```swift struct ContentView: View { let date = Date.now let price: Decimal = 9.99 let progress = 0.75 var body: some View { VStack { // Dates Text(date, format: Date.FormatStyle(date: .complete, time: .complete)) Text(date, format: .dateTime.hour()) Text(date, format: .dateTime.year().month().day()) // Numbers Text(price, format: .currency(code: "USD")) Text(progress, format: .percent) // Duration Text(Duration.seconds(125), format: .time(pattern: .minuteSecond)) } } } ``` -------------------------------- ### Replace Legacy Formatting with FormatStyle Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Demonstrates the correct modern Swift FormatStyle replacements for common legacy formatting anti-patterns. Use these examples to migrate existing code. ```swift String(format: "%.2f", value) String(format: "%02d:%02d", minutes, seconds) String(format: "%d%%", percentage) String(format: "$%.2f", price) ``` ```swift value.formatted(.number.precision(.fractionLength(2))) Duration.seconds(totalSeconds).formatted(.time(pattern: .minuteSecond)) percentage.formatted(.percent) price.formatted(.currency(code: "USD")) ``` ```swift let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter.string(from: date) ``` ```swift date.formatted(date: .abbreviated, time: .shortened) ``` ```swift let minutes = Int(seconds) / 60 let secs = Int(seconds) % 60 return String(format: "%02d:%02d", minutes, secs) ``` ```swift Duration.seconds(seconds).formatted(.time(pattern: .minuteSecond)) // Output: "16:40" ``` ```swift // Legacy → Modern mapping: // NumberFormatter → .formatted(.number) / FloatingPointFormatStyle / IntegerFormatStyle // DateFormatter → .formatted(.dateTime) / Date.FormatStyle // DateComponentsFormatter → Duration.formatted(.units()) / Duration.formatted(.time(...)) // DateIntervalFormatter → .formatted(.interval) / Date.IntervalFormatStyle // MeasurementFormatter → .formatted(.measurement(...)) // PersonNameComponentsFormatter → .formatted(.name(style:)) // ByteCountFormatter → .formatted(.byteCount(style:)) // RelativeDateTimeFormatter → .formatted(.relative(...)) ``` -------------------------------- ### Trigger Swift Format Style Skill in Codex Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md Example of how to trigger the Swift Format Style skill in Codex. Specific instructions can be provided for partial reviews. ```bash $swift-format-style Fix the date formatting in this file ``` -------------------------------- ### Parsing Numbers with FormatStyle Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Provides examples of parsing strings into numbers using FormatStyle, including specifying notation. Use `try?` for optional parsing and ensure the string format matches the specified style. ```swift try? Int("120", format: .number) // 120 try? Double("0.0025", format: .number) // 0.0025 try? Int("1E5", format: .number.notation(.scientific)) // 100000 ``` -------------------------------- ### Trigger Swift Format Style Skill in Claude Code Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/README.md Example of how to trigger the Swift Format Style skill in Claude Code. Specific instructions can be provided for partial reviews. ```bash /swift-format-style Replace all String(format:) calls with FormatStyle ``` -------------------------------- ### Direct Initialization of Number Format Styles Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Illustrates direct initialization of format styles for precise control over formatting. ```swift FloatingPointFormatStyle().rounded(rule: .up, increment: 1).format(10.9) // "11" IntegerFormatStyle().notation(.compactName).format(1_000) // "1K" Decimal.FormatStyle().scale(10).format(1) // "10" ``` -------------------------------- ### Date Interval Formatting in Swift Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Formats a date range or interval, displaying both start and end points. Supports various granularities like year, month, and hour. ```swift let range = date1...Currency(code: "JPY").rounded(rule: .up, increment: 1).format(10.9) // "¥11" IntegerFormatStyle.Currency(code: "GBP").presentation(.fullName).format(42) // "42.00 British pounds" Decimal.FormatStyle.Currency(code: "USD").scale(12).format(0.1) // "$1.20" ``` -------------------------------- ### Number Notation Formatting Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Explains how to format numbers using different notations like .compactName and .scientific. Useful for displaying large numbers concisely or in scientific contexts. ```swift Float(1_000).formatted(.number.notation(.compactName)) // "1K" Float(1_000).formatted(.number.notation(.scientific)) // "1E3" ``` -------------------------------- ### Date and Time Presets Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Utilize predefined styles for formatting dates and times quickly. Supports various levels of detail for both date and time components. ```swift twosday.formatted(date: .abbreviated, time: .omitted) // "Feb 22, 2022" twosday.formatted(date: .complete, time: .omitted) // "Tuesday, February 22, 2022" twosday.formatted(date: .long, time: .omitted) // "February 22, 2022" twosday.formatted(date: .numeric, time: .omitted) // "2/22/2022" twosday.formatted(date: .omitted, time: .complete) // "2:22:22 AM MST" twosday.formatted(date: .omitted, time: .shortened) // "2:22 AM" twosday.formatted(date: .omitted, time: .standard) // "2:22:22 AM" twosday.formatted(date: .abbreviated, time: .shortened) // "Feb 22, 2022, 2:22 AM" ``` -------------------------------- ### Implement Custom FormatStyle (Swift) Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Create custom formatting and parsing logic by conforming to `FormatStyle` and `ParseableFormatStyle`. Allows defining input/output conversions and registering shorthand accessors. ```swift // Minimal custom style struct CelsiusToFahrenheitStyle: FormatStyle { func format(_ value: Double) -> String { let f = value * 9 / 5 + 32 return f.formatted(.number.precision(.fractionLength(1))) + "°F" } func locale(_ locale: Locale) -> Self { self } } // Register dot-syntax shorthand extension FormatStyle where Self == CelsiusToFahrenheitStyle { static var celsiusToFahrenheit: CelsiusToFahrenheitStyle { .init() } } // Usage 25.0.formatted(.celsiusToFahrenheit) // "77.0°F" ``` ```swift // Bidirectional style (format + parse) struct TemperatureParseStrategy: ParseStrategy { func parse(_ value: String) throws -> Double { guard let f = Double(value.dropLast(2)) else { throw ParseError() } return (f - 32) * 5 / 9 } } struct BidirectionalTempStyle: ParseableFormatStyle { typealias FormatInput = Double typealias FormatOutput = String func format(_ value: Double) -> String { value.formatted(.celsiusToFahrenheit) } func locale(_ locale: Locale) -> Self { self } var parseStrategy: TemperatureParseStrategy { .init() } } ``` -------------------------------- ### Number Sign Display Strategies Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Shows how to control the display of number signs using strategies like .never, .always(), and .always(includingZero: true). This is important for clarity in different contexts. ```swift Float(1.90).formatted(.number.sign(strategy: .never)) // "1.9" Float(1.90).formatted(.number.sign(strategy: .always())) // "+1.9" Float(0).formatted(.number.sign(strategy: .always(includingZero: true))) // "+0" ``` -------------------------------- ### Custom ISO 8601 Configuration Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Configure ISO 8601 formatting with custom separators, fractional second inclusion, and specific time zones. ```swift let isoFormat = Date.ISO8601FormatStyle( dateSeparator: .dash, dateTimeSeparator: .standard, timeSeparator: .colon, timeZoneSeparator: .colon, includingFractionalSeconds: true, timeZone: TimeZone(secondsFromGMT: 0)! ) isoFormat.format(twosday) // "2022-02-22T09:22:22.000Z" ``` -------------------------------- ### Presentation Styles for Currency in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Control how currency is presented, choosing between full name, ISO code, narrow symbol, or standard symbol. ```swift Decimal(10).formatted(.currency(code: "GBP").presentation(.fullName)) // "10.00 British pounds" Decimal(10).formatted(.currency(code: "GBP").presentation(.isoCode)) // "GBP 10.00" Decimal(10).formatted(.currency(code: "GBP").presentation(.narrow)) // "£10.00" Decimal(10).formatted(.currency(code: "GBP").presentation(.standard)) // "£10.00" ``` -------------------------------- ### Format File Size using Text(format:) Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/SKILL.md Integrate byte count formatting directly into SwiftUI `Text` views using the `format:` parameter, avoiding string interpolation with `.formatted()`. This is the recommended approach for SwiftUI. ```swift // Before Text("\(fileSize.formatted(.byteCount(style: .file)))") // After Text(fileSize, format: .byteCount(style: .file)) ``` -------------------------------- ### Compositing Currency Format Styles in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Combine multiple currency formatting options, such as scale, sign strategy, and presentation, to create a custom format. ```swift Decimal(10).formatted(.currency(code: "GBP").scale(200.0).sign(strategy: .always()).presentation(.fullName)) // "+2,000.00 British pounds" ``` -------------------------------- ### Basic Number Formatting Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Demonstrates the basic usage of the `.formatted()` method for different numeric types. ```swift 32.formatted() // "32" Decimal(20.0).formatted() // "20" Float(10.0).formatted() // "10" Double(100.0003).formatted() // "100.0003" ``` -------------------------------- ### Number Precision Formatting Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Demonstrates formatting numbers with specific precision using .significantDigits and .fractionLength, or a combination for integer and fraction parts. Essential for accurate data representation. ```swift Decimal(10.1).formatted(.number.precision(.significantDigits(4))) // "10.10" Decimal(10.01).formatted(.number.precision(.fractionLength(1))) // "10.0" Decimal(10.111).formatted( .number.precision(.integerAndFractionLength(integer: 2, fraction: 1))) // "10.1" ``` -------------------------------- ### Number Formatting with Sign Strategies Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Controls the display of signs for positive, negative, and zero numbers using various strategies. ```swift Float(1.90).formatted(.number.sign(strategy: .never)) // "1.9" Float(-1.90).formatted(.number.sign(strategy: .never)) // "1.9" Float(1.90).formatted(.number.sign(strategy: .always())) // "+1.9" Float(0).formatted(.number.sign(strategy: .always(includingZero: true))) // "+0" Float(0).formatted(.number.sign(strategy: .always(includingZero: false))) // "0" ``` -------------------------------- ### Format Custom Measurement Unit Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Demonstrates formatting with custom units. Custom units are typically displayed using the .asProvided usage, as the system may not have built-in localization for them. ```swift // One-off custom unit let smoots = UnitLength(symbol: "smoot", converter: UnitConverterLinear(coefficient: 1.70180)) let bridgeLength = Measurement(value: 364.4, unit: smoots) bridgeLength.formatted(.measurement(width: .abbreviated, usage: .asProvided)) // "364.4 smoot" // Extending an existing Dimension extension UnitSpeed { static let furlongPerFortnight = UnitSpeed( symbol: "fur/ftn", converter: UnitConverterLinear(coefficient: 201.168 / 1209600.0) ) } ``` -------------------------------- ### Number Formatting with Decimal Separator Strategies Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Configures the display of the decimal separator, with options for automatic or always showing it. ```swift Float(10).formatted(.number.decimalSeparator(strategy: .automatic)) // "10" Float(10).formatted(.number.decimalSeparator(strategy: .always)) // "10." ``` -------------------------------- ### Verbatim Date Formatting Pitfalls Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Highlights critical considerations for verbatim date formatting, emphasizing the necessity of explicit locale specification to avoid garbled output and explaining how `.autoupdatingCurrent` locale affects calendar usage. ```swift // WRONG - nil locale gives garbled output Date.VerbatimFormatStyle( format: "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", timeZone: .current, calendar: .current ).format(twosday) // "2022-M02-22" <- broken, not "2022-Feb-22" // CORRECT - always provide locale Date.VerbatimFormatStyle( format: "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", locale: Locale(identifier: "en_US"), timeZone: .current, calendar: .current ).format(twosday) // "2022-Feb-22" ``` ```swift // Locale .autoupdatingCurrent ignores calendar Date.VerbatimFormatStyle( format: "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", locale: .autoupdatingCurrent, timeZone: .autoupdatingCurrent, calendar: Calendar(identifier: .buddhist) ).format(twosday) // "2022-Feb-22" <- ignores Buddhist calendar // Explicit locale respects calendar Date.VerbatimFormatStyle( format: "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", locale: Locale(identifier: "en_US"), timeZone: .autoupdatingCurrent, calendar: Calendar(identifier: .buddhist) ).format(twosday) // "2565-Feb-22" <- correct Buddhist year ``` -------------------------------- ### Number Formatting with Notation Styles Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Applies different notation styles to format numbers, including automatic, compact names, and scientific notation. ```swift Float(1_000).formatted(.number.notation(.automatic)) // "1,000" Float(1_000).formatted(.number.notation(.compactName)) // "1K" Float(1_000).formatted(.number.notation(.scientific)) // "1E3" ``` -------------------------------- ### SwiftUI Text Formatting: Correct vs. Incorrect Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/swiftui.md Demonstrates the incorrect use of string interpolation with `.formatted()` and the correct use of the `format:` parameter in SwiftUI's `Text` view. ```swift // WRONG Text("\(value.formatted(.number.precision(.fractionLength(2))))") Text("\(date.formatted(.dateTime.hour().minute()))") // CORRECT Text(value, format: .number.precision(.fractionLength(2))) Text(date, format: .dateTime.hour().minute()) ``` -------------------------------- ### Format URL with Component Control (Swift) Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Format `URL` values with fine-grained control over component visibility (scheme, user, host, etc.). Supports parsing URLs with default, optional, or required port specifications. Requires Xcode 14+. ```swift let url = URL(string: "https://apple.com")! url.formatted() // "https://apple.com" url.formatted(.url) // "https://apple.com" ``` ```swift // Fine-grained component control let style = URL.FormatStyle( scheme: .always, user: .never, password: .never, host: .always, port: .always, path: .always, query: .never, fragment: .never ) style.format(url) // "https://apple.com" ``` ```swift // Parsing try URL.FormatStyle.Strategy(port: .defaultValue(80)).parse("http://www.apple.com") // http://www.apple.com:80 try URL.FormatStyle.Strategy(port: .optional).parse("http://www.apple.com") // http://www.apple.com try URL.FormatStyle.Strategy(port: .required).parse("http://www.apple.com") // throws error — no port present ``` -------------------------------- ### Sign Strategies for Currency in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Control how signs are displayed for currency values using various strategies like `.automatic`, `.never`, `.always()`, and accounting styles. ```swift Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .automatic)) // "£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .never)) // "£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accounting)) // "£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accountingAlways())) // "+£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accountingAlways(showZero: true))) // "+£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accountingAlways(showZero: false))) // "+£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .always())) // "+£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .always(showZero: true))) // "+£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .always(showZero: false))) // "+£7.00" ``` -------------------------------- ### Parsing Formatted Numbers Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Demonstrates how to parse strings into numeric types using specified number format styles. ```swift try? Int("120", format: .number) // 120 try? Int("1E5", format: .number.notation(.scientific)) // 100000 try? Double("0.0025", format: .number) // 0.0025 try? Decimal("1E5", format: .number.notation(.scientific)) // 100000 ``` -------------------------------- ### Configure URL Component Display Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Defines a `URL.FormatStyle` to control the display of individual URL components like scheme, user, host, and path. Options include `.always`, `.never`, and conditional display. ```swift let style = URL.FormatStyle( scheme: .always, user: .never, password: .never, host: .always, port: .always, path: .always, query: .never, fragment: .never ) ``` -------------------------------- ### SwiftUI Stopwatch using FormatStyle.stopwatch Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Implements a live-updating stopwatch in SwiftUI using the `.stopwatch` format style. Requires Xcode 16+. ```swift struct Stopwatch: View { @State var startDate: Date? @State var isRunning = false var body: some View { if isRunning { Text(TimeDataSource.currentDate, format: .stopwatch(startingAt: startDate ?? .now)) } else { Text(Date.now, format: .stopwatch(startingAt: startDate ?? .now)) } Button("Start") { startDate = .now; isRunning = true } } } ``` -------------------------------- ### Custom Date Format with Locale and Calendar Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Create a custom date format style specifying locale, calendar, time zone, and capitalization context for advanced formatting needs. ```swift let frenchHebrew = Date.FormatStyle( date: .complete, time: .complete, locale: Locale(identifier: "fr_FR"), calendar: Calendar(identifier: .hebrew), timeZone: TimeZone(secondsFromGMT: 0)!, capitalizationContext: .standalone ) twosday.formatted(frenchHebrew) // "Mardi 22 fevrier 2022 ap. J.-C. 9:22:22 UTC" ``` -------------------------------- ### Number Grouping and Locale Formatting Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Shows how to format numbers with automatic grouping and specify locales for culturally appropriate formatting. This ensures numbers are displayed correctly across different regions. ```swift Float(1000).formatted(.number.grouping(.automatic)) // "1,000" Float(1_000).formatted(.number.notation(.compactName).locale(Locale(identifier: "fr_FR"))) // "1 k" ``` -------------------------------- ### ISO 8601 Formatting Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Format a date into the standard ISO 8601 string representation. This is a common format for data exchange. ```swift twosday.formatted(.iso8601) // "2022-02-22T09:22:22Z" ``` -------------------------------- ### Format Measurement by Usage and Locale Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Formats a Measurement using specific usage types (.general, .asProvided, .personHeight) and locales. .general uses locale-appropriate units, while .asProvided retains the original unit. ```swift let myHeight = Measurement(value: 190, unit: UnitLength.centimeters) myHeight.formatted(.measurement(width: .abbreviated, usage: .general).locale(Locale(identifier: "en-US"))) // "6.2 ft" myHeight.formatted(.measurement(width: .abbreviated, usage: .asProvided).locale(Locale(identifier: "en-US"))) // "190 cm" myHeight.formatted(.measurement(width: .abbreviated, usage: .personHeight).locale(Locale(identifier: "en-US"))) // "6 ft, 2.8 in" ``` -------------------------------- ### Format Person Name Components Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Demonstrates formatting `PersonNameComponents` into various string representations. Use `.formatted()` for default, `.abbreviated`, `.short`, `.medium`, or `.long` styles. ```swift let guest = PersonNameComponents( namePrefix: "Dr", givenName: "Elizabeth", middleName: "Jillian", familyName: "Smith", nameSuffix: "Esq.", nickname: "Liza" ) guest.formatted() // "Elizabeth Smith" guest.formatted(.name(style: .abbreviated)) // "ES" guest.formatted(.name(style: .short)) // "Liza" guest.formatted(.name(style: .medium)) // "Elizabeth Smith" guest.formatted(.name(style: .long)) // "Dr Elizabeth Jillian Smith Esq." ``` ```swift guest.formatted(.name(style: .medium).locale(Locale(identifier: "zh_CN"))) ``` ```swift try? PersonNameComponents.FormatStyle().parseStrategy.parse("Dr Elizabeth Jillian Smith Esq.") ``` -------------------------------- ### SwiftUI AttributedString Formatting for Percentages Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/swiftui.md Demonstrates how to obtain an `AttributedString` with styled runs for percentage formatting in SwiftUI. This allows for granular styling of integer, fraction, and symbol parts of the formatted number. ```swift struct ContentView: View { var percentAttributed: AttributedString { var result = 0.8890.formatted(.percent.attributed) result.swiftUI.font = .title result.runs.forEach { run in if let numberRun = run.numberPart { switch numberRun { case .integer: result[run.range].foregroundColor = .orange case .fraction: result[run.range].foregroundColor = .blue } } if let symbolRun = run.numberSymbol { switch symbolRun { case .percent: result[run.range].foregroundColor = .green case .decimalSeparator: result[run.range].foregroundColor = .red default: break } } } return result } var body: some View { Text(percentAttributed) } } ``` -------------------------------- ### Basic Time Formatting Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Format a Duration into a human-readable time string. Defaults to hours, minutes, and seconds. ```swift Duration.seconds(1_000).formatted() // "0:16:40" ``` ```swift Duration.seconds(1_000).formatted(.time(pattern: .hourMinute)) // "0:17" ``` ```swift Duration.seconds(1_000).formatted(.time(pattern: .hourMinuteSecond)) // "0:16:40" ``` ```swift Duration.seconds(1_000).formatted(.time(pattern: .minuteSecond)) // "16:40" ``` -------------------------------- ### Number Formatting with Rounding Rules Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Applies different rounding rules to format numbers, specifying the rounding behavior and increment. ```swift Float(5.01).formatted(.number.rounded(rule: .awayFromZero, increment: 1)) // "6" Float(5.01).formatted(.number.rounded(rule: .awayFromZero, increment: 10)) // "10" Float(5.01).formatted(.number.rounded(rule: .down, increment: 1)) // "5" ``` -------------------------------- ### Avoid C-style String(format:) for numbers Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/anti-patterns.md Never format numbers with `String(format:)`. Use the modern `.formatted()` method with appropriate styles like `.number`, `.percent`, or `.currency`. ```swift // WRONG - C-style formatting String(format: "%.2f", value) String(format: "%02d:%02d", minutes, seconds) String(format: "%d%%", percentage) String(format: "$%.2f", price) ``` ```swift // CORRECT - FormatStyle value.formatted(.number.precision(.fractionLength(2))) Duration.seconds(totalSeconds).formatted(.time(pattern: .minuteSecond)) percentage.formatted(.percent) price.formatted(.currency(code: "USD")) ``` -------------------------------- ### Formatting Percentages in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Use the `.percent` style for formatting numbers as percentages. Integer percentages are treated literally, while floating-point numbers are treated as fractions. ```swift 0.1.formatted(.percent) // "10%" ``` ```swift Float(0.26575).formatted(.percent.rounded(rule: .awayFromZero)) // "26.575%" Float(1.90).formatted(.percent.sign(strategy: .always())) // "+189.999998%" Float(1_000).formatted(.percent.grouping(.automatic)) // "100,000%" Float(1_000).formatted(.percent.grouping(.never)) // "100000%" Float(1_000).formatted(.percent.notation(.compactName)) // "100K%" Float(10).formatted(.percent.scale(2.0)) // "20%" ``` -------------------------------- ### Avoid manual duration formatting Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/anti-patterns.md Agents frequently build manual duration formatting. Use the built-in `Duration.formatted(.time(...))` styles instead. ```swift // WRONG - manual calculation let minutes = Int(seconds) / 60 let secs = Int(seconds) % 60 return String(format: "%02d:%02d", minutes, secs) ``` ```swift // CORRECT - Duration.TimeFormatStyle Duration.seconds(seconds).formatted(.time(pattern: .minuteSecond)) // Output: "16:40" ``` ```swift // WRONG - manual hours:minutes:seconds let h = Int(seconds) / 3600 let m = (Int(seconds) % 3600) / 60 let s = Int(seconds) % 60 return String(format: "%d:%02d:%02d", h, m, s) ``` ```swift // CORRECT Duration.seconds(seconds).formatted(.time(pattern: .hourMinuteSecond)) // Output: "0:16:40" ``` -------------------------------- ### Basic Units Formatting Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Format a Duration using named units. Defaults to a combination of minutes and seconds. ```swift Duration.seconds(100).formatted(.units()) // "1 min, 40 sec" ``` -------------------------------- ### Number Formatting with Grouping Options Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Specifies how thousands separators are displayed, with options for automatic or no grouping. ```swift Float(1000).formatted(.number.grouping(.automatic)) // "1,000" Float(1000).formatted(.number.grouping(.never)) // "1000" ``` -------------------------------- ### Define Custom FormatStyle Protocol Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Shows the definition of the `FormatStyle` protocol, which requires `FormatInput` and `FormatOutput` associated types and `format` and `locale` methods. This protocol is used for custom formatting. ```swift public protocol FormatStyle: Decodable, Encodable, Hashable { associatedtype FormatInput associatedtype FormatOutput func format(_ value: Self.FormatInput) -> Self.FormatOutput func locale(_ locale: Locale) -> Self } ``` -------------------------------- ### Units Style with Allowed Units Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Specify which units are allowed in the formatted output. This controls the granularity and types of units displayed, from nanoseconds to weeks. ```swift Duration.milliseconds(500).formatted(.units(allowed: [.nanoseconds])) // "500,000,000 ns" ``` ```swift Duration.milliseconds(500).formatted(.units(allowed: [.microseconds])) // "500,000 us" ``` ```swift Duration.milliseconds(500).formatted(.units(allowed: [.milliseconds])) // "500 ms" ``` ```swift Duration.milliseconds(500).formatted(.units(allowed: [.seconds])) // "0 sec" ``` ```swift Duration.seconds(1_000_000.00123).formatted( .units(allowed: [.nanoseconds, .milliseconds, .seconds, .minutes, .hours, .days, .weeks]) ) // "1 wk, 4 days, 13 hr, 46 min, 40 sec, 1 ms, 230,000 ns" ``` -------------------------------- ### Day Component Options Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Specify the format for the day component, such as two digits, default digits, or ordinal. ```swift .day(.twoDigits) // "22" .day(.defaultDigits) // "22" .day(.ordinalOfDayInMonth) // "4" ``` -------------------------------- ### Time Style with Padding and Rounding Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Customize the hour minute pattern by padding hours and rounding seconds. Use `padHourToLength` for fixed-width hours and `roundSeconds` to control rounding behavior. ```swift Duration.seconds(1_000).formatted(.time(pattern: .hourMinute(padHourToLength: 3, roundSeconds: .awayFromZero))) // "000:17" ``` ```swift Duration.seconds(1_000).formatted(.time(pattern: .hourMinute(padHourToLength: 1, roundSeconds: .down))) // "000:16" ``` -------------------------------- ### Compositing Number Format Modifiers Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Shows how to combine multiple formatting modifiers for advanced number styling. ```swift Float(10).formatted(.number.scale(200.0).notation(.compactName).grouping(.automatic)) // "2K" ``` -------------------------------- ### Formatting Currency in Swift (JPY) Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Format numbers as currency using the `.currency` style, specifying the ISO 4217 currency code. Always use `Decimal` for currency values. ```swift 10.formatted(.currency(code: "JPY")) // "¥10" ``` -------------------------------- ### Format URL Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Formats a `URL` into its string representation. The `.url` style is equivalent to the default `.formatted()` for URLs and is available from Xcode 14+. ```swift let url = URL(string: "https://apple.com")! url.formatted() // "https://apple.com" url.formatted(.url) // "https://apple.com" ``` -------------------------------- ### Extend FormatStyle for Dot Syntax Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Demonstrates how to make a custom `FormatStyle` available via dot syntax by extending `FormatStyle` where `Self` matches the custom style type. This allows for usage like `value.formatted(.myStyle)`. ```swift extension FormatStyle where Self == MyCustomStyle { static var myStyle: MyCustomStyle { .init() } } ``` -------------------------------- ### Units Style with Fractional Part Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Configure the display of the fractional part of a unit. Options include hiding, showing with specified length, rounding, or incrementing. ```swift Duration.seconds(10.0_023).formatted(.units(fractionalPart: .hide)) // "10 sec" ``` ```swift Duration.seconds(10.0_023).formatted(.units(fractionalPart: .hide(rounded: .up))) // "11 sec" ``` ```swift Duration.seconds(10.0_023).formatted(.units(fractionalPart: .show(length: 5))) // "10.00230 sec" ``` ```swift Duration.seconds(10.0_023).formatted(.units(fractionalPart: .show(length: 3, rounded: .up))) // "10.003 sec" ``` ```swift Duration.seconds(10.0_023).formatted(.units(fractionalPart: .show(length: 3, increment: 0.001))) // "10.002 sec" ``` -------------------------------- ### Swift Currency Formatting Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Format `Decimal` values as currency using ISO 4217 codes. Supports rounding, presentation styles (full name, ISO code, narrow), and sign strategies. Locale can be specified for regional formatting. Parsing is also supported. ```swift // Basic 10.formatted(.currency(code: "JPY")) // "¥10" Decimal(10).formatted(.currency(code: "GBP")) // "£10.00" ``` ```swift // Rounding Decimal(0.599).formatted(.currency(code: "GBP").rounded()) // "£0.60" Decimal(5.001).formatted(.currency(code: "GBP").rounded(rule: .awayFromZero)) // "£5.01" ``` ```swift // Presentation Decimal(10).formatted(.currency(code: "GBP").presentation(.fullName)) // "10.00 British pounds" Decimal(10).formatted(.currency(code: "GBP").presentation(.isoCode)) // "GBP 10.00" Decimal(10).formatted(.currency(code: "GBP").presentation(.narrow)) // "£10.00" ``` ```swift // Sign strategies Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accounting)) // "£7.00" Decimal(7).formatted(.currency(code: "GBP").sign(strategy: .accountingAlways())) // "+£7.00" ``` ```swift // Composed Decimal(10).formatted( .currency(code: "GBP").scale(200.0).sign(strategy: .always()).presentation(.fullName) ) // "+2,000.00 British pounds" ``` ```swift // Locale Decimal(10).formatted( .currency(code: "GBP").presentation(.fullName).locale(Locale(identifier: "fr_FR")) ) // "10,00 livres sterling" ``` ```swift // Parsing try Decimal("$3.14", format: .currency(code: "USD").locale(Locale(identifier: "en_US"))) // 3.14 ``` -------------------------------- ### Locale-Specific Currency Formatting in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/numeric-styles.md Format currency according to specific locale conventions for language and regional number/currency formatting. ```swift Decimal(10).formatted(.currency(code: "GBP").presentation(.fullName).locale(Locale(identifier: "fr_FR")) // "10,00 livres sterling" Decimal(10000000).formatted(.currency(code: "GBP").locale(Locale(identifier: "hi_IN"))) // "£1,00,00,000.00" ``` -------------------------------- ### Parse Dates Using Format Styles in Swift Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/date-styles.md Parse date strings into `Date` objects using `Date.FormatStyle` or by initializing `Date` with a custom parsing strategy. This allows for flexible conversion of various date and time formats. ```swift try? Date.FormatStyle() .day().month().year().hour().minute().second() .parse("Feb 22, 2022, 2:22:22 AM") ``` ```swift try? Date( "Feb 22, 2022, 2:22:22 AM", strategy: Date.FormatStyle().day().month().year().hour().minute().second().parseStrategy ) ``` -------------------------------- ### Specify locale explicitly with .verbatim() Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/anti-patterns.md When using `.verbatim()`, always specify the locale explicitly. Omitting it defaults to `nil` and can produce broken output. ```swift // WRONG - nil locale date.formatted(.verbatim( "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", timeZone: .current, calendar: .current )) // "2022-M02-22" <- broken ``` ```swift // CORRECT date.formatted(.verbatim( "\(year: .defaultDigits)-\(month: .abbreviated)-\(day: .twoDigits)", locale: Locale(identifier: "en_US"), timeZone: .current, calendar: .current )) // "2022-Feb-22" ``` -------------------------------- ### Time Style with Fractional Seconds Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/duration-styles.md Format time with fractional seconds, controlling padding, length, and rounding. `padHourToLength` and `padMinuteToLength` affect the respective units, while `fractionalSecondsLength` and `roundFractionalSeconds` manage the decimal part. ```swift Duration.seconds(1_000).formatted( .time(pattern: .hourMinuteSecond(padHourToLength: 3, fractionalSecondsLength: 3, roundFractionalSeconds: .awayFromZero)) ) // "000:16:40.000" ``` ```swift Duration.seconds(1_000).formatted( .time(pattern: .minuteSecond(padMinuteToLength: 3, fractionalSecondsLength: 3, roundFractionalSeconds: .awayFromZero)) ) // "016:40.000" ``` -------------------------------- ### Swift ISO 8601 Date Formatting Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Format dates into ISO 8601 strings. Allows custom configuration for separators, fractional seconds, and time zones. Parsing of ISO 8601 strings into `Date` objects is also supported. ```swift twosday.formatted(.iso8601) // "2022-02-22T09:22:22Z" ``` ```swift // Custom configuration let isoFormat = Date.ISO8601FormatStyle( dateSeparator: .dash, dateTimeSeparator: .standard, timeSeparator: .colon, timeZoneSeparator: .colon, includingFractionalSeconds: true, timeZone: TimeZone(secondsFromGMT: 0)! ) isoFormat.format(twosday) // "2022-02-22T09:22:22.000Z" ``` ```swift // Parsing try? Date.ISO8601FormatStyle(timeZone: TimeZone(secondsFromGMT: 0)!) .year().day().month() .dateSeparator(.dash).dateTimeSeparator(.standard).timeSeparator(.colon) .time(includingFractionalSeconds: true) .parse("2022-02-22T09:22:22.000") // Feb 22, 2022, 2:22:22 AM ``` -------------------------------- ### Parse URL with Default Port Source: https://github.com/n0an/swift-formatstyle-agent-skill/blob/main/swift-format-style/references/other-styles.md Parses a URL string using a `URL.FormatStyle.Strategy` that specifies a default port. If the port is not present in the string, the default is appended. ```swift try URL.FormatStyle.Strategy(port: .defaultValue(80)).parse("http://www.apple.com") // http://www.apple.com:80 ``` ```swift try URL.FormatStyle.Strategy(port: .optional).parse("http://www.apple.com") // http://www.apple.com ``` ```swift try URL.FormatStyle.Strategy(port: .required).parse("http://www.apple.com") // throws error ``` -------------------------------- ### Date Components Formatting in Swift Source: https://context7.com/n0an/swift-formatstyle-agent-skill/llms.txt Displays the difference between two dates in plain language using named units. Supports different styles (abbreviated, condensed, spellOut, wide) and field selections. ```swift let range = date1..