swift-foundation

repository·main·Indexed 25 days ago

https://github.com/swiftlang/swift-foundation

A shared implementation of Foundation APIs providing essential utility types (numbers, data, collections, dates) and functions (task management, file system access) for Swift applications. It includes modules such as FoundationEssentials and FoundationInternationalization to ensure consistency across all Swift platforms. While available as a Swift package, it is intended strictly for development and testing of Foundation and is not supported as a dependency for shipping projects.

Tokens
55.5K
Snippets
122
Records
277
Agent score
80%

What's inside swift-foundation

  1. Overview of the Subprocess package

    main
    The Subprocess package is a modern replacement for the legacy Foundation Process (formerly NSTask) API. It is designed to provide a more ergonomic experience for process creation in Swift, specifically addressing the lack of async/await support and the reliance on Objective-C patterns in the original API. It is intended for use in scripting, server-side development, and general-purpose compiled applications.
  2. Overview of FoundationEssentials

    main

    The FoundationEssentials library provides a foundational layer of functionality for apps and frameworks. It includes essential data types, collections, and operating-system services required to build base-layer application logic.

    Key capabilities include:

    • Data storage and persistence
    • Text processing
    • Basic date and time calculations
    • Sorting and filtering operations
  3. Overview of ProgressManager for Swift Concurrency

    main

    The ProgressManager API is a new progress reporting mechanism for Foundation designed specifically for Swift's async/await concurrency model. It addresses the limitations of the existing Progress class when used with structured concurrency by providing a type-safe, error-resistant architecture that separates progress composition from progress observation.

    Key features include:

    • Swift Concurrency Integration: Enables incremental progress reporting within async/await patterns.
    • Decoupled Task Control: Focuses strictly on reporting progress, leaving task cancellation to Swift's native concurrency primitives (though it reacts to cancellation by completing progress upon deinit).
    • Swift Observation Support: Uses the @Observable macro to allow UI components to bind to progress information reactively.
    • Type-Safe Extensibility: Allows attaching custom metadata (properties) to progress metrics.
    • Dual Use Case Support: Supports both function-level and class-level progress reporting, including multi-parent support via ProgressReporter.
  4. Understand Foundation components and modules

    main

    Foundation is composed of several distinct layers depending on your platform and requirements:

    Swift Foundation

    Shared library in the Swift toolchain written in Swift. Provides core types (URL, Data, JSONDecoder, Locale, Calendar) via FoundationEssentials and FoundationInternationalization modules.

    Swift Corelibs Foundation

    Shared library in the Swift toolchain (Swift and C) providing compatibility for pre-Swift APIs. It provides NSObject, class-based data structures, NSFormatter, and NSKeyedArchiver. It re-exports FoundationEssentials and FoundationInternationalization. Note: compatibility is best-effort as implementations differ from Objective-C.

    Foundation ICU

    A private library wrapping ICU, used by FoundationInternationalization. If you do not need ICU-based internationalization, import FoundationEssentials instead to avoid this dependency.

    Foundation Framework

    Built into macOS, iOS, and Darwin platforms. It is a combination of C, Objective-C, and Swift that compiles swift-foundation sources into a single Foundation module.

  5. Understand the Progress Reporting API types

    main

    The new progress reporting API consists of three primary types designed to handle progress trees safely in concurrent environments:

    1. ProgressManager: A mutable reference type used to manage and compose progress. It is used to track counts and assign subtasks. It is Sendable and Observable.
    2. ProgressReporter: A read-only representation of a ProgressManager. It is used for observing progress (e.g., binding to UI components) or for constructing multi-parent acyclic graphs where a single subtask might contribute to multiple parents.
    3. Subprogress: An intuitive type used to report on subtasks and compose them as part of a progress graph.
  6. Understand Subprocess traits

    main

    The Subprocess package uses Swift package traits to manage dependencies and API availability:

    • SubprocessFoundation: Enabled by default starting in Swift 6.1. It adds a dependency on Foundation and provides extensions on Foundation types like Data.
    • SubprocessSpan: Enabled whenever Span is available. It makes the API (primarily OutputProtocol) RawSpan based.

    For Swift 6.0 and earlier, SubprocessFoundation is essentially always enabled, and SubprocessSpan is essentially always disabled.

  7. Use Calendar.RecurrenceRule for repeating events

    main
    The Calendar.RecurrenceRule structure allows you to describe how often an event should repeat, modeling a subset of the iCalendar RFC-5545 and RFC-7529 specifications. It is designed to work with both Gregorian and non-Gregorian calendars. This API enables the enumeration of dates that match a specific recurrence pattern (e.g., "Yearly" or "Every 1st Saturday of the month").
  8. Propose a minor API enhancement

    main

    Minor enhancements—such as extending existing types with new functions/variables or adding new case to an enum—can use an abbreviated review process if they have already gained community interest via GitHub issues or forum threads.

    1. Develop the proposal: Prepare a proposal using the proposal template including a prototype.
    2. Request an abbreviated review:
    3. Management: A workgroup member will be assigned to manage the review. The manager will comment on the forum pitch if it is suitable for this abbreviated path and communicate next steps.
    4. Feedback and Acceptance: Address feedback as needed. The review manager will accept the proposal if there is broad agreement among the community and the workgroup.
  9. Write and maintain tests

    main

    Follow these rules when writing tests for swift-foundation:

    • Avoid crashes in tests: Do not force unwrap in tests. Use try or #require so that failures are reported as test failures rather than process crashes.
    • Avoid print statements: Do not use print in tests; use assertions instead.
    • Ensure relevance: Tests must be relevant to the changed code path. A test should fail before a fix is applied and pass after.
    • Use parameterized testing: Pass test inputs as arguments rather than hardcoding them, utilizing the Swift Testing API's parameterized testing features.
    • Test process exits: When adding precondition, preconditionFailure, or fatalError, use #expect(processExitsWith:) to verify the process terminates correctly under invalid input.
    • Measure performance: Use swift-benchmark for performance measurements. Add entries under the Benchmarks/ directory and ensure setup code is outside the measured scope.
  10. Handle platform-specific code and flags

    main

    Implementation and tests should work on all supported platforms by default. Use platform-specific logic only when necessary:

    • Use #if os(...) sparingly: Only use platform conditionals when behavior genuinely differs or the API is unavailable on a specific platform.
    • Explain divergences: Always add comments to platform conditionals explaining why the code diverges.
    • Be specific with flags: Avoid broad flags like NO_LOCALIZATION. Use explicit checks, such as || os(OpenBSD), accompanied by a comment explaining the specific platform requirement.
  11. Use Foundation on non-Apple platforms

    main

    On non-Apple platforms (where Foundation is not built into the OS), the API is available via the Swift toolchain. You can access the core functionality by importing the specific modules required for your task:

    • Use import FoundationEssentials for core types like URL, Data, JSONDecoder, Locale, and Calendar.
    • Use import FoundationInternationalization for internationalization features (which relies on the Foundation ICU library).

    Alternatively, these modules are re-exported from the Foundation, FoundationXML, and FoundationNetworking modules in swift-corelibs-foundation.

    import FoundationEssentials
    // or
    import FoundationInternationalization
  12. Use Regex within Swift Predicates

    main

    You can use Swift Regex types or regex literals within a #Predicate to perform complex pattern matching on strings. This provides feature parity with NSPredicate's MATCHES operator.

    To perform a whole-string match (matching the entire string rather than just finding a substring), ensure you include start (^) and end ($) anchors in your regex.

    Availability: FoundationPreview 0.4 or later.

    // Using a Regex builder
    let regex = Regex {
    	Anchor.startOfSubject
    	Repeat(.digit, count: 5)
    	Optionally {
    		"-"
    		Repeat(.digit, count: 4)
    	}
    	Anchor.endOfSubject
    }
    
    let predicate = #Predicate<Address> {
    	$0.zipcode.contains(regex)
    }
    
    // OR using a regex literal for a whole-string match
    let predicate = #Predicate<Address> {
    	$0.zipcode.contains(/^\d{5}(-\d{4})?$/)
    }