Convert Figma logo to code with AI

swiftlang logoswift-corelibs-foundation

The Foundation Project, providing core utilities, internationalization, and OS independence

5,271
1,132
5,271
658

Top Related Projects

67,740

The Swift Programming Language

The libdispatch Project, (a.k.a. Grand Central Dispatch), for concurrency on multicore hardware

The Package Manager for the Swift Programming Language

Event-driven network application framework for high performance protocol servers & clients, non-blocking.

Plugin and runtime library for using protobuf with Swift

24,473

💧 A server-side Swift HTTP web framework.

Quick Overview

Swift-corelibs-foundation is an open-source implementation of Apple's Foundation framework for Swift on Linux and other platforms. It provides a set of fundamental tools and data types that form the basis for many Swift applications, including networking, file system access, and data management.

Pros

  • Cross-platform compatibility, enabling Swift development on non-Apple platforms
  • Open-source nature allows for community contributions and customizations
  • Provides a familiar API for iOS/macOS developers working on other platforms
  • Continually updated to maintain parity with Apple's Foundation framework

Cons

  • May have some inconsistencies or missing features compared to Apple's implementation
  • Performance might not be as optimized as the native Apple version on macOS/iOS
  • Requires separate maintenance and updates to keep up with Apple's changes
  • Some platform-specific features may not be available or fully implemented

Code Examples

  1. Working with URLs and URLSession:
import Foundation

let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let data = data {
        let jsonString = String(data: data, encoding: .utf8)
        print(jsonString ?? "No data received")
    }
}
task.resume()
  1. File management:
import Foundation

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("example.txt")

let content = "Hello, Swift!"
try? content.write(to: fileURL, atomically: true, encoding: .utf8)

if let readContent = try? String(contentsOf: fileURL) {
    print("File content: \(readContent)")
}
  1. Date and time manipulation:
import Foundation

let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: now)
print("Current date and time: \(dateString)")

let calendar = Calendar.current
let tomorrow = calendar.date(byAdding: .day, value: 1, to: now)!
print("Tomorrow: \(formatter.string(from: tomorrow))")

Getting Started

To use swift-corelibs-foundation in your Swift project on Linux or other non-Apple platforms:

  1. Install Swift for your platform: https://swift.org/download/
  2. Create a new Swift package:
    mkdir MyProject
    cd MyProject
    swift package init --type executable
    
  3. Edit Package.swift to include Foundation:
    // swift-tools-version:5.5
    import PackageDescription
    
    let package = Package(
        name: "MyProject",
        dependencies: [
            .package(url: "https://github.com/apple/swift-corelibs-foundation.git", .branch("main"))
        ],
        targets: [
            .executableTarget(
                name: "MyProject",
                dependencies: ["Foundation"])
        ]
    )
    
  4. Build and run your project:
    swift build
    swift run
    

Competitor Comparisons

67,740

The Swift Programming Language

Pros of swift

  • Comprehensive language implementation, including compiler and standard library
  • Supports multiple platforms (iOS, macOS, Linux, Windows)
  • Active development with frequent updates and new features

Cons of swift

  • Larger codebase, potentially more complex to navigate
  • Longer build times due to the full language implementation
  • Steeper learning curve for contributors

Code comparison

swift:

public struct Array<Element> {
    public init()
    public init(repeating repeatedValue: Element, count: Int)
    public var count: Int { get }
    public var isEmpty: Bool { get }
    public subscript(index: Int) -> Element
}

swift-corelibs-foundation:

open class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
    open var count: Int { get }
    open func object(at index: Int) -> Any
    open func index(of object: Any) -> Int
    open func contains(_ anObject: Any) -> Bool
    open subscript(index: Int) -> Any { get }
}

The swift repository contains the core language implementation, including the Array type as a struct with generics. In contrast, swift-corelibs-foundation provides Objective-C compatible classes like NSArray, which are reference types and use Any for element types.

The libdispatch Project, (a.k.a. Grand Central Dispatch), for concurrency on multicore hardware

Pros of swift-corelibs-libdispatch

  • Focused on concurrent and asynchronous task management
  • Lightweight and efficient for handling parallel execution
  • Provides a unified API for managing queues and tasks

Cons of swift-corelibs-libdispatch

  • Limited scope compared to the broader Foundation framework
  • Requires more manual management of concurrency patterns
  • Less comprehensive documentation and community resources

Code Comparison

swift-corelibs-libdispatch:

let queue = DispatchQueue(label: "com.example.queue")
queue.async {
    print("Async task executed")
}

swift-corelibs-foundation:

let url = URL(string: "https://example.com")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    print("Network request completed")
}
task.resume()

Summary

swift-corelibs-libdispatch is a specialized library for managing concurrent and asynchronous tasks, offering a streamlined API for queue management and task execution. It excels in scenarios requiring fine-grained control over parallel processing.

swift-corelibs-foundation, on the other hand, provides a broader set of utilities and abstractions for common programming tasks, including networking, file management, and data processing. It offers a more comprehensive toolkit for building full-featured applications.

While libdispatch focuses on concurrency primitives, Foundation encompasses a wider range of functionality, making it more suitable for general-purpose development. Developers often use both libraries in conjunction, leveraging libdispatch for low-level concurrency control and Foundation for higher-level application features.

The Package Manager for the Swift Programming Language

Pros of swift-package-manager

  • Focused on package management and dependency resolution
  • Provides a command-line interface for easy project management
  • Integrates well with Swift projects and the Swift ecosystem

Cons of swift-package-manager

  • Limited to package management functionality
  • May require additional tools for full application development
  • Less comprehensive than Foundation in terms of general-purpose utilities

Code Comparison

swift-package-manager:

import PackageDescription

let package = Package(
    name: "MyPackage",
    dependencies: [
        .package(url: "https://github.com/example/example-package.git", from: "1.0.0"),
    ]
)

swift-corelibs-foundation:

import Foundation

let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    // Handle the response
}
task.resume()

The swift-package-manager code focuses on defining package dependencies, while swift-corelibs-foundation provides a wide range of utilities, such as networking in this example. swift-corelibs-foundation offers a broader set of functionalities for application development, whereas swift-package-manager specializes in managing project dependencies and structure.

Event-driven network application framework for high performance protocol servers & clients, non-blocking.

Pros of swift-nio

  • Focused on high-performance networking, optimized for server-side Swift applications
  • Provides a more modern, event-driven architecture for networking tasks
  • Actively maintained and regularly updated by Apple and the community

Cons of swift-nio

  • Narrower scope compared to swift-corelibs-foundation, focusing primarily on networking
  • Steeper learning curve for developers accustomed to traditional Foundation networking APIs
  • May require additional dependencies for full functionality in some use cases

Code Comparison

swift-corelibs-foundation (URLSession):

let url = URL(string: "https://api.example.com")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    // Handle response
}
task.resume()

swift-nio (ClientBootstrap):

let bootstrap = ClientBootstrap(group: group)
    .connectTimeout(.seconds(30))
    .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
    .channelInitializer { channel in
        channel.pipeline.addHandler(HTTPClientRequestEncoder()).flatMap {
            channel.pipeline.addHandler(HTTPClientResponseDecoder())
        }
    }

swift-nio provides more granular control over networking operations but requires more setup code compared to the simpler URLSession API in swift-corelibs-foundation. swift-nio is better suited for complex, high-performance networking scenarios, while swift-corelibs-foundation offers a more familiar and straightforward API for basic networking tasks.

Plugin and runtime library for using protobuf with Swift

Pros of swift-protobuf

  • Specialized for Protocol Buffers, offering optimized performance for serialization and deserialization
  • Provides a more lightweight and focused solution for working with Protocol Buffers in Swift
  • Includes code generation tools for creating Swift types from .proto files

Cons of swift-protobuf

  • Limited scope compared to the broader functionality of swift-corelibs-foundation
  • May require additional dependencies for features not directly related to Protocol Buffers
  • Less integrated with the Swift standard library and ecosystem

Code Comparison

swift-protobuf:

import SwiftProtobuf

let message = MyMessage()
message.id = 123
message.name = "Example"
let data = try message.serializedData()

swift-corelibs-foundation:

import Foundation

let dictionary = ["id": 123, "name": "Example"]
let data = try JSONSerialization.data(withJSONObject: dictionary)

The swift-protobuf example demonstrates direct serialization of a Protocol Buffer message, while swift-corelibs-foundation shows JSON serialization using Foundation's built-in capabilities. swift-protobuf is more specialized for Protocol Buffers, while swift-corelibs-foundation provides a broader range of functionality for various data formats and standard library extensions.

24,473

💧 A server-side Swift HTTP web framework.

Pros of Vapor

  • Designed specifically for web development, offering a more streamlined and focused API
  • Includes built-in features like routing, templating, and ORM, reducing the need for additional dependencies
  • Active community and frequent updates, ensuring better support and modern Swift compatibility

Cons of Vapor

  • Smaller ecosystem compared to Foundation, which may limit available resources and third-party libraries
  • Steeper learning curve for developers not familiar with web-specific concepts
  • May have performance overhead in certain scenarios due to its higher-level abstractions

Code Comparison

Swift-corelibs-foundation (basic HTTP request):

let url = URL(string: "https://api.example.com")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    // Handle response
}
task.resume()

Vapor (basic HTTP route):

app.get("hello") { req -> String in
    return "Hello, world!"
}

The Foundation example shows a low-level approach to making HTTP requests, while Vapor demonstrates a high-level routing mechanism for handling HTTP requests in a web application context.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Foundation

The Foundation framework defines a base layer of functionality that is required for almost all applications. It provides primitive classes and introduces several paradigms that define functionality not provided by either the Objective-C runtime and language or Swift standard library and language.

It is designed with these goals in mind:

  • Provide a small set of basic utility classes and data structures.
  • Make software development easier by introducing consistent conventions.
  • Support internationalization and localization, to make software accessible to users around the world.
  • Provide a level of OS independence, to enhance portability.

There is more information on the Foundation framework here.

This project, swift-corelibs-foundation, provides an compatibility implementation of the Foundation API for platforms where there is no Objective-C runtime. On macOS, iOS, and other Apple platforms, apps should use the Foundation that comes with the operating system.

Project Navigator

Foundation builds in different configurations and is composed of several projects.

  graph TD;
      FF[Foundation.framework]-->SF
      subgraph GitHub
        SCLF[swift-corelibs-foundation]-->SF
        SF[swift-foundation]-->FICU[swift-foundation-icu]
        SF-->SC[swift-collections]
      end   

Swift Foundation

A shared library shipped in the Swift toolchain, written in Swift. It provides the core implementation of many key types, including URL, Data, JSONDecoder, Locale, Calendar, and more in the FoundationEssentials and FoundationInternationalization modules. Its source code is shared across all platforms.

swift-foundation depends on a limited set of packages, primarily swift-collections and swift-syntax.

Swift Corelibs Foundation

A shared library shipped in the Swift toolchain. It provides compatibility API for clients that need pre-Swift API from Foundation. It is written in Swift and C. It provides, among other types, NSObject, class-based data structures, NSFormatter, and NSKeyedArchiver. It re-exports the FoundationEssentials and FoundationInternationalization modules, allowing compatibility for source written before the introduction of the swift-foundation project. As these implementations are distinct from those written in Objective-C, the compatibility is best-effort only.

swift-corelibs-foundation builds for non-Darwin platforms only. It installs the Foundation umbrella module, FoundationXML, and FoundationNetworking.

Foundation ICU

A private library for Foundation, wrapping ICU. Using a standard version of ICU provides stability in the behavior of our internationalization API, and consistency with the latest releases on Darwin platforms. It is imported from the FoundationInternationalization module only. Clients that do not need API that relies upon the data provided by ICU can import FoundationEssentials instead.

Foundation Framework

A framework built into macOS, iOS, and all other Darwin platforms. It is written in a combination of C, Objective-C, and Swift. The Foundation framework compiles the sources from swift-foundation into its binary and provides one Foundation module that contains all features.

Using Foundation

Here is a simple main.swift file which uses Foundation. This guide assumes you have already installed a version of the latest Swift binary distribution.

import Foundation

// Make a URLComponents instance
let swifty = URLComponents(string: "https://swift.org")!

// Print something useful about the URL
print("\(swifty.host!)")

// Output: "swift.org"

You will want to use the Swift Package Manager to build your Swift apps.

Working on Foundation

swift-corelibs-foundation builds as a standalone project using Swift Package Manager. Simply use swift build in the root of the checkout to build the project.

swift-corelibs-foundation also builds as part of the toolchain for non-Darwin platforms. Instructions on building the toolchain are available in the Swift project.

Contributions

We welcome contributions to Foundation! Please see the known issues page if you are looking for an area where we need help. We are also standing by on the mailing lists to answer questions about what is most important to do and what we will accept into the project.