The Swift Programming Language

Swift logo

Swift Programming Language

Architecture main Package
macOS x86_64 Build Status Build Status
Ubuntu 16.04 x86_64 Build Status Build Status
Ubuntu 18.04 x86_64 Build Status Build Status
Ubuntu 20.04 x86_64 Build Status Build Status
CentOS 8 x86_64 Build Status Build Status
CentOS 7 x86_64 Build Status Build Status
Amazon Linux 2 x86_64 Build Status Build Status

Swift Community-Hosted CI Platforms

OS Architecture Build
Ubuntu 16.04 PPC64LE Build Status
Ubuntu 18.04 AArch64 Build Status
Ubuntu 20.04 AArch64 Build Status
Ubuntu 20.04 wasm32 Build Status
Android ARMv7 Build Status
Android AArch64 Build Status
Windows 2019 (VS 2017) x86_64 Build Status
Windows 2019 (VS 2019) x86_64 Build Status

Welcome to Swift

Swift is a high-performance system programming language. It has a clean and modern syntax, offers seamless access to existing C and Objective-C code and frameworks, and is memory safe by default.

Although inspired by Objective-C and many other languages, Swift is not itself a C-derived language. As a complete and independent language, Swift packages core features like flow control, data structures, and functions, with high-level constructs like objects, protocols, closures, and generics. Swift embraces modules, eliminating the need for headers and the code duplication they entail.

To learn more about the programming language, visit swift.org.

Contributing to Swift

Contributions to Swift are welcomed and encouraged! Please see the Contributing to Swift guide.

To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.

To give clarity of what is expected of our members, Swift has adopted the code of conduct defined by the Contributor Covenant. This document is used across many open source communities, and we think it articulates our values well. For more, see the Code of Conduct.

Getting Started

If you are interested in:

We also have an FAQ that answers common questions.

Swift Toolchains

Building

Swift toolchains are created using the script build-toolchain. This script is used by swift.org's CI to produce snapshots and can allow for one to locally reproduce such builds for development or distribution purposes. A typical invocation looks like the following:

  $ ./swift/utils/build-toolchain $BUNDLE_PREFIX

where $BUNDLE_PREFIX is a string that will be prepended to the build date to give the bundle identifier of the toolchain's Info.plist. For instance, if $BUNDLE_PREFIX was com.example, the toolchain produced will have the bundle identifier com.example.YYYYMMDD. It will be created in the directory you run the script with a filename of the form: swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz.

Beyond building the toolchain, build-toolchain also supports the following (non-exhaustive) set of useful options::

  • --dry-run: Perform a dry run build. This is off by default.
  • --test: Test the toolchain after it has been compiled. This is off by default.
  • --distcc: Use distcc to speed up the build by distributing the c++ part of the swift build. This is off by default.
  • --sccache: Use sccache to speed up subsequent builds of the compiler by caching more c++ build artifacts. This is off by default.

More options may be added over time. Please pass --help to build-toolchain to see the full set of options.

Installing into Xcode

On macOS if one wants to install such a toolchain into Xcode:

  1. Untar and copy the toolchain to one of /Library/Developer/Toolchains/ or ~/Library/Developer/Toolchains/. E.x.:
  $ sudo tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz -C /
  $ tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz -C ~/

The script also generates an archive containing debug symbols which can be installed over the main archive allowing symbolication of any compiler crashes.

  $ sudo tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx-symbols.tar.gz -C /
  $ tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx-symbols.tar.gz -C ~/
  1. Specify the local toolchain for Xcode's use via Xcode->Toolchains.

Build Failures

Try the suggestions in Troubleshooting build issues.

Make sure you are using the correct release of Xcode.

If you have changed Xcode versions but still encounter errors that appear to be related to the Xcode version, try passing --clean to build-script.

When a new version of Xcode is released, you can update your build without recompiling the entire project by passing --reconfigure to build-script.

Learning More

Be sure to look at the documentation index for a bird's eye view of the available documentation. In particular, the documents titled Debugging the Swift Compiler and Continuous Integration for Swift are very helpful to understand before submitting your first PR.

Comments
  • +0 Guaranteed Arguments

    +0 Guaranteed Arguments

    This PR contains the final work to convert the compiler to +0. There are still some tests failing, but I would like to get start performing PR testing of the branch.

  • test: migrate tests to Python3 by default

    test: migrate tests to Python3 by default

    This changes the python interpreter used to invoke the tests to Python3. Python2 has been EOL'ed by the Python Software Foundation. This migration enables the Swift test suite to run with Python 3 instead.

    Replace this paragraph with a description of your changes and rationale. Provide links to external references/discussions if appropriate.

    Resolves SR-NNNN.

  • [DO NOT MERGE] [WIP] StringGuts

    [DO NOT MERGE] [WIP] StringGuts

    An initial implementation of a more resilient 2-word representation for String. It uses BridgeObject (for now) to achieve a high degree of resilience. In the future, we'll add more small string forms, establish UnsafeString, and generally rejigger String's views to be properly layered on top.

    Notes:

    • Self slices are currently implemented by forming _NSContiguousStrings to hold the sliced up _StringCore. This incurs overhead. Long term, we could support owned self slices, but for now it would be fruitful to try to eliminate all uses of self-slicing _StringCore from the stdlib. The most common occurrence (but by no means the only) is through _ephemeralString. Instead, for anything that can't possibly escape, we should convert to an UnsafeString, guarantee the lifetime, and slice that up.

    • We cannot utilize small representations effectively until we start to wean ourselves off of _LegacyStringCore. Ideally (depending on project planning needs) we would be fully weaned off before adding small representations. We'd also like to get close to performance parity where it matters prior, to better gauge the impact of such optimizations.

    • The spiritual predecessor to this effort is at https://github.com/dabrahams/swift/commits/string-recore, and while the physical implementation differs, that's a great demonstration of what we're trying to accomplish.

  • [metadata prespecialization] Support for classes.

    [metadata prespecialization] Support for classes.

    When generic metadata for a class is requested in the same module where the class is defined, rather than a call to the generic metadata accessor or to a variant of typeForMangledNode, a call to a new accessor--a canonical specialized generic metadata accessor--is emitted. The new function is defined schematically as follows:

        MetadataResponse `canonical specialized metadata accessor for C<K>`(MetadataRequest request) {
          (void)`canonical specialized metadata accessor for superclass(C<K>)`(::Complete)
          (void)`canonical specialized metadata accessor for generic_argument_class(C<K>, 1)`(::Complete)
          ...
          (void)`canonical specialized metadata accessor for generic_argument_class(C<K>, count)`(::Complete)
          auto *metadata = objc_opt_self(`canonical specialized metadata for C<K>`);
          return {metadata, MetadataState::Complete};
        }
    

    To enable these new canonical specialized generic metadata accessors, metadata for generic classes is prespecialized as needed. So are the metaclasses and the corresponding rodata.

    Previously, the lazy objc naming hook was registered during process execution when the first generic class metadata was instantiated. Since that instantiation may occur "before process launch" (i.e. if the generic metadata is prespecialized), the lazy naming hook is now installed at process launch.

  • Add support for calling C++ constructors

    Add support for calling C++ constructors

    A problem that we have to deal with when calling C++ constructors is that the ABI of a C++ constructor depends not only on the signature of the constructor but on the class on which it is defined. For example, it can be necessary to pass additional “implicit” arguments to constructors of virtual base classes.

    It is therefore fundamentally not possible for SignatureExpansion (which doesn’t have access to the CXXConstructorDecl) to reliably produce the correct LLVM signature from only the type of the constructor. The approach we take is to try to get most of the way in SignatureExpansion by marking the SIL function return type with the @out attribute, representing the fact that C++ constructors take a this points to the object to be initialized.

    This produces an “assumed” constructor ABI in SignatureExpansion that assumes there are no implicit arguments and that the return type of the constructor ABI is void (and indeed there is no way to represent anything else in the SIL type). If this assumed ABI doesn’t match the actual ABI, we insert a thunk in IRGen.

    The thunk is marked alwaysinline, so it doesn’t incur any runtime overhead, but some compile-time overhead is required for LLVM to inline the thunk. If this turns out to be excessive, we can introduce what is essentially a peephole optimization for a full apply of a function_refthat refers to a C++ constructor and directly emit the constructor call in this case (along with any required implicit arguments) instead of calling the thunk. I’ve chosen not to tackle that in this PR though as it’s already large enough.

    On some ABIs (e.g. Itanium x64), we get lucky and the ABI for a complete constructor call always matches the assumed ABI.

    In addition to the core C++ constructor functionality, this PR adds some a couple of small required features:

    • Conversion of thin to a Clang void type
    • Handling of formal indirect results in SignatureExpansion::expandExternalSignatureTypes()
  • Smol String

    Smol String

    Add in small strings, plumb all APIs through, etc. There's some current performance issues, namely that small string support introduces branching and our default implementation technique involves spilling to the stack and calling _UnmanagedString methods. The first is unavoidable (although we're planning a better overall branching strategy to reduce this impact), the second is TODO.

  • [CS] Use fixes to diagnose instance member on type (or vice versa) access

    [CS] Use fixes to diagnose instance member on type (or vice versa) access

    This PR migrates instance member on type and type member on instance diagnostics handling to use the new diagnostics framework (fixes) and create more reliable and accurate diagnostics in such scenarios.

  • [SE-0283] Implement Equatable, Comparable, and Hashable conformance for Tuples

    [SE-0283] Implement Equatable, Comparable, and Hashable conformance for Tuples

    From: https://forums.swift.org/t/hacking-equatable-conformance-on-void/25975

    The tests right now are kind of lackluster, what else can I be testing with this? What else can be improved upon in this implementation? Is there an edge case that I hadn't thought about?

    cc: @jckarter @rjmccall

  • [SR-381] API to lookup a Type given a top-level class name

    [SR-381] API to lookup a Type given a top-level class name

    | | | |------------------|-----------------| |Previous ID | SR-381 | |Radar | None | |Original Reporter | @lhoward | |Type | New Feature | |Status | Closed | |Resolution | Done |

    Additional Detail from JIRA

    | | | |------------------|-----------------| |Votes | 1 | |Component/s | Standard Library | |Labels | New Feature, AffectsABI, Runtime | |Assignee | @jckarter | |Priority | Medium |

    md5: 13f1c2ae7174aab8983f1dde3a976c53

    blocks:

    • SR-377 Implement NSKeyed[Un]Archiver

    relates to:

    • SR-412 Linux: Cannot define C function pointer that returns metaclass

    Issue Description:

    This may be useful to implement NSStringFromClass()-compatible behaviour which is necessary in order to implement NSKeyedArchiver. I am using the attached workaround at the moment but obviously it is very fragile.

  • [DNM] String interpolation rework

    [DNM] String interpolation rework

    Implements apple/swift-evolution#904.

    This is the implementation of the string interpolation rework. It is now feature-complete, but there are still a few things on my to-do list:

    • ~~It's performing similarly to the current design overall, although individual benchmarks vary wildly—from 1.80x for StringInterpolationSmall to 0.59x for FloatingPointPrinting_Float_interpolated. (Some of the improvements in tests which have little to do with string interpolation are probably thanks to new overloads of String.init(describing:) I added to preserve source compatibility.) We want it to be faster than the status quo. I haven't dug deeply into this yet, and I'd like a second opinion from the CI.~~

    • I'm wondering if it would be useful for DefaultStringInterpolation to become moveonly in the future, and if so, if that could be done without breaking ABI compatibility. @rjmccall, what do you think?

    • There are a couple of test failures I'm not sure what to do with:

      • ~~Constraints/rdar42678836.swift was apparently added three days ago and has already had its message change twice. @slavapestov, @xedin, can we pin down what this test ought to do?~~

      • IDE/complete_at_top_level.swift fails because we don't suggest a Void function in a string interpolation. I think that comes from this line, which looks like it's intended to prevent you from completing a Void function where a value is expected, but I'm just guessing at its purpose. Can anyone clear up my confusion and help me figure out what this should be doing? (@nkcsgexi wrote this, but it was years ago.)

    @swift-ci Please benchmark

    cc @milseman

  • [SE-0287] [Sema] Implementation for implicit member chains

    [SE-0287] [Sema] Implementation for implicit member chains

    This is the implementation for a forthcoming proposal (see this discussion thread) that extends implicit member syntax to allow additional member accesses chained off of the base UnresolvedMemberExpr.

    Resolves: rdar://problem/57295228

  • Slow compilation when using Array.max(by:) with Array literal directly

    Slow compilation when using Array.max(by:) with Array literal directly

    Describe the bug We recently encountered a slowdown in the compilation process of our app. Upon closer investigation it turned our that the culprit was an Array literal used in conjunction with the Array.max(by:) function.

    To Reproduce Steps to reproduce the behavior:

    1. Create the following swift file main.swift:
      public struct Foo {
          let title: String
          let description: String?
      }
      
      let a = Foo(title: "A", description: "a")
      let b = Foo(title: "B", description: "b")
      
      // 1. Compiles slowly
      if let maximum = [a, b].max(by: { $0.title.count + ($0.description?.count ?? 0) < $1.title.count + ($1.description?.count ?? 0) }) { print(maximum) }
      
      // 2. Compiles quickly
      // let ab = [a, b]
      // if let maximum = ab.max(by: { $0.title.count + ($0.description?.count ?? 0) < $1.title.count + ($1.description?.count ?? 0) }) { print(maximum) }
      
    2. Compile with time swiftc main.swift and note the compilation time
    3. Comment out the 1. Compiles slowly section and uncomment section 2. Compiles quickly
    4. Compile with time swiftc main.swift and note the compilation time

    Expected behavior Both cases compile within an equivalent timeframe.

    Screenshots Screenshot 2022-05-18 at 14 34 42

    Environment:

    • OS: macOS 12.3
    • Xcode Version: 13.0

    I tried Xcode 13.0 embedded toolchain and org.swift.57202205151a toolchain. The issue was present in both.

  • [stdlib] Work around binary compatibility issues with String index validation fixes in 5.7

    [stdlib] Work around binary compatibility issues with String index validation fixes in 5.7

    Swift 5.7 added stronger index validation for String, so some illegal cases that previously triggered inconsistently diagnosed out of bounds accesses now result in reliable runtime errors. Similarly, attempts at applying an index originally vended by a UTF-8 string on a UTF-16 string now result in a reliable runtime error.

    As is usually the case, new traps to the stdlib exposes code that contains previously undiagnosed / unreliably diagnosed coding issues.

    Allow invalid code in binaries built with earlier versions of the stdlib to continue running with the 5.7 library by disabling some of the new traps based on the version of Swift the binary was built with.

    In the case of an index encoding mismatch, allow transcoding of string storage regardless of the direction of the mismatch. (Previously we only allowed transcoding a UTF-8 string to UTF-16.)

    rdar://93379333

  • [CSSimplify] Disfavor choices that have injected `callAsFunction`

    [CSSimplify] Disfavor choices that have injected `callAsFunction`

    Ambiguities like:

    struct S {
      init(v: Int) {}
      init(v: Int, _: () -> Void) {}
    
      func callAsFunction(_: () -> Void) {}
    }
    
    S(v: 42) {
    }
    

    Should always be resolved in favor of choice that doesn't require injection of .callAsFunction, so let's try to avoid solving if such an overload has already been found.

  • [5.7][Parser] Allow parsing `any` in structural position within enum associated value types.

    [5.7][Parser] Allow parsing `any` in structural position within enum associated value types.

    Cherry-pick of https://github.com/apple/swift/pull/58950

    • Explanation: any does not parse in structural types within enum associated value types. This change allows the following code to compile:
    protocol P {}
    
    enum E {
      case hello((any P) -> Void)
    }
    
    • Scope: This change simply calls into Parser::startsParameterName, which already supports looking for contextual any and some, instead of repeating the code without checking for contextual keywords in Parser::canParseTypeTupleBody.
    • Risk: Low.
    • Testing: Added new unit tests.
    • Reviewer: @DougGregor

    Resolves: rdar://93382182

  • [5.7][Parse] Set missing contextual keyword token kind for `async`

    [5.7][Parse] Set missing contextual keyword token kind for `async`

    Cherry-picks 862f3fc4206b19b98dbda27e6d7c258a4bcf7344 (https://github.com/apple/swift/pull/58912) which fixes async to be a contextual keyword rather than an identifier.


    Resolves rdar://93080331.

Related tags
Swift Framework for Apple Health Integration with Terra Enabling Developers LTD.

TerraSwift This library allows developers to connect to TERRA ENABLING DEVELOPERS LTD. through Swift (implemented with Swift5.0). This library uses He

Mar 18, 2022
PoC of Swift for [email protected]

FastlyEdgeExample An example project to deploy Swift code to Fastly's [email protected] Requirements SwiftWasm toolchain fastly CLI How to deploy $ fastly

Feb 28, 2022
PLP Project Programming Language | Programming for projects and computer science and research on computer and programming.
PLP Project Programming Language | Programming for projects and computer science and research on computer and programming.

PLPv2b PLP Project Programming Language Programming Language for projects and computer science and research on computer and programming. What is PLP L

Apr 11, 2022
StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that of JavaScript's and TypeScript's

StarkScript StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that

May 10, 2022
frost is a programming language with a focus on low-friction systems programming.

❄️ frost frost programming language About frost is a programming language with a focus on low-friction systems programming.

Nov 12, 2021
The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.

Wren is a small, fast, class-based concurrent scripting language Think Smalltalk in a Lua-sized package with a dash of Erlang and wrapped up in a fami

May 20, 2022
Competitive Programming - Programming👨‍💻 Questions on BinarySearch💻, LeetCode💻, CodeChef💻, Codeforces💻,DSA 450
Competitive Programming - Programming👨‍💻  Questions on BinarySearch💻, LeetCode💻, CodeChef💻, Codeforces💻,DSA 450

?? Hacktoberfest2021 ?? This repository is open to all members of the GitHub community. Any member can contribute. Contribute according to the steps g

May 12, 2022
J is an array programming language

J: From C to C++20 J is an array programming language created by Ken Iverson and Roger Hui (see image below).

May 11, 2022
A minimal viable programming language on top of liblgpp

This project aims to implement a minimal viable programming language on top of liblgpp. setup The project requires a C++17 compiler, CMake and liblgpp

Jun 28, 2021
A perfect blend of C, Java, and Python tailored for those who desire a simple yet powerful programming language.

Fastcode A perfect blend of C, Java, and Python tailored for those who desire a simple yet powerful programming language. FastCode is a procedural/str

Apr 18, 2022
Loop is an object oriented programming language
Loop is an object oriented programming language

Loop Loop is an object oriented programming language. How do I build and run loop? Make sure, you installed the requirements for clang and make: Debia

Aug 9, 2021
C implementation of the Monkey programming language.
C implementation of the Monkey programming language.

Development of this interpreter continues here: dannyvankooten/pepper-lang C implementation of the Monkey programming language. Bytecode compiler and

Feb 1, 2022
A programming language made in C

1. Fang A programming language made in C 1.1. Meaning Fang stands for "Feline Language". In hopes of it being cool like a cat! On top of it, you can b

Apr 8, 2021
AHHH: a programming language for the dreadful
AHHH: a programming language for the dreadful

AHHH: a programming language for the dreadful Screaming into the Void but make it Turing Complete AHHH is an esoteric programming language inspired by

Apr 7, 2022
Pandex is a light but FAST programming language written in C . Pandex goal is that be hard & it's good for eductional goals

The Pandex programming language version 1.0.0.3 Pandex versions release type The Pandex version has four numbers. the first number holds 1 ( or 0 in s

Jan 4, 2022
Arobase is a simple programming language with a c-like syntax.
Arobase is a simple programming language with a c-like syntax.

Arobase Arobase is a simple programming language with a c-like syntax. Requirements gcc gas (gnu as) ld A 64 bits linux distribution (generated assemb

Apr 22, 2022
C+- is a personal project trying to make a programming language.
C+- is a personal project trying to make a programming language.

C+- A personal project trying to be a programming language with close resemblence to C/C++ (probably gonna fail at that).

Mar 26, 2022
Simple String_View implementation for C programming language.

Simple String_View implementation for C programming language.

Apr 2, 2022