{
  "id": "enwiki-001379000016",
  "slug": "swift-programming-language",
  "title": "Swift (programming language)",
  "qid": "",
  "lead": "Swift is a high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code and uses an LLVM-based compiler. Swift was first released in June 2014 and the Swift toolchain has shipped in Xcode since Xcode version 6, released in September 2014. Apple intended Swift to support many core concepts associated with Objective-C, notably dynamic dispatch, widespread late binding, extensible programming, and similar features, but in a \"safer\" way, making it easier to catch software bugs; Swift has features addressing some common programming errors like null pointer dereferencing and provides syntactic sugar to help avoid the pyramid of doom. Swift supports the concept of protocol extensibility, an extensibility system that can be applied to types, structs and classes, which Apple promotes as a real change in programming paradigms they term \"protocol-oriented programming\" (similar to traits and type classes). Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a major upgrade to Swift 2 at WWDC 2015. It was initially a proprietary language, but version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple's platforms and Linux.",
  "body": "Swift is a high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code and uses an LLVM-based compiler. Swift was first released in June 2014 and the Swift toolchain has shipped in Xcode since Xcode version 6, released in September 2014. Apple intended Swift to support many core concepts associated with Objective-C, notably dynamic dispatch, widespread late binding, extensible programming, and similar features, but in a \"safer\" way, making it easier to catch software bugs; Swift has features addressing some common programming errors like null pointer dereferencing and provides syntactic sugar to help avoid the pyramid of doom. Swift supports the concept of protocol extensibility, an extensibility system that can be applied to types, structs and classes, which Apple promotes as a real change in programming paradigms they term \"protocol-oriented programming\" (similar to traits and type classes). Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a major upgrade to Swift 2 at WWDC 2015. It was initially a proprietary language, but version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple's platforms and Linux. Swift's \"Hello, World!\" program is: print(\"Hello, world!\") The function used here is included in Swift's standard library, which is available to all programs without the need to import external modules. Statements in Swift don't have to end with a semicolon, however semicolons are required to separate multiple statements written on the same line. Single-line comments begin with and continue until the end of the current line. Multiline comments are contained by and characters. Constants (variables which cannot be modified) are declared with the keyword, while variables declared using the keyword can change. Values must be initialised before they are read. Variables may infer their type based on the type of the provided initial value. If the initial value is set after the value's declaration, a type must be declared explicitly. let highScoreThreshold = 1000 // A constant with type Int. The type was inferred based on the provided value. var currentScore = 980 // A variable with type Int. currentScore = 1200 // The value of variables can change over time. let playerMessage: String // A constant with explicit type String. if currentScore > highScoreThreshold { playerMessage = \"You are a top player!\" } else { playerMessage = \"Better luck next time.\" } print(playerMessage) // Prints \"You are a top player!\" Control flow in Swift is managed with if-else, guard, and switch statements, along with while and for-in loops. The statements take a Boolean parameter and execute the body of the statement if the condition is true, otherwise it executes the optional body. syntax provides syntactic sugar for checking for the existence of an optional value and unwrapping it at the same time. let someNumber = 42 if someNumber % 2 == 0 { // Use the remainder operator to find the remainder of someNumber divided by 2. print(\"\\(someNumber) is even.\") } else { print(\"\\(someNumber) is odd.\") } // Prints \"42 is even.\" Functions are defined with the keyword. Function parameters may have names which allow function calls to read like phrases. An underscore before the parameter name allows the argument label to be omitted from the call site. Tuples can be used by functions to return multiple pieces of data at once. func constructGreeting(for name: String) -> String { return \"Hello \\(name)!\" } let greeting = constructGreeting(for: \"Craig\") print(greeting) // Prints \"Hello Craig!\" Functions, and anonymous functions known as closures, can be assigned to properties and passed around the program like any other value. func divideByTwo(_ aNum: Int) -> Int { return aNum / 2 } func multiplyByTwo(_ aNum: Int) -> Int { return aNum * 2 } let mathOperation = multiplyByTwo print(mathOperation(21)) // Prints \"42\" statements require that the given condition is true before continuing on past the statement, otherwise the body of the provided clause is run. The clause must exit control of the code block in which the statement appears. statements are useful for ensuring that certain requirements are met before continuing on with program execution. In particular they can be used to create an unwrapped version of an optional value that is guaranteed to be non-nil for the remainder of the enclosing scope. func divide(numerator: Int?, byDenominator denominator: Int) -> Int? { guard denominator != 0 else { print(\"Can't divide by 0.\") return nil } guard let numerator else { print(\"The provided numerator is nil.\") return nil } return numerator / denominator } let result = divide(numerator: 3, byDenominator: 0) print(\"Division result is: \\(result)\") // Prints: // \"Can't divide by 0.\" // \"Division result is: nil.\" switch statements compare a value with multiple potential values and then executes an associated code block. switch statements must be made exhaustive, either by including cases for all possible values or by including a default case which is run when the provided value doesn't match any of the other cases. switch cases do not implicitly fall through, although they may explicitly do so with the fallthrough keyword. Pattern matching can be used in various ways inside switch statements. Here is an example of an integer being matched against a number of potential ranges: let someNumber = 42 switch someNumber { case .. for-in loops iterate over a sequence of values: let names = [\"Will\", \"Anna\", \"Bart\"] for name in names { print(name) } // Prints: // Will // Anna // Bart while loops iterate as long as the given Boolean condition evaluates to true : // Add together all the numbers from 1 to 5. var i = 1 var result = 0 while i // Closure type, defined by its input and output values, can be specified outside the closure: let closure1: (Int, Int) -> Int = { arg1, arg2 in return arg1 + arg2 } // …or inside it: let closure2 = { (arg1: Int, arg2: Int) -> Int in return arg1 + arg2 } // In most cases, closure's return type can be inferred automatically by the compiler. let closure3 = { arg1: Int, arg2: Int in return arg1 + arg2 } Closures can be assigned to variables and constants, and can be passed into other functions or closures as parameters. Single-expression closures may drop the keyword. Swift also has a trailing closure syntax, which allows the closure to be written after the end of the function call instead of within the function's parameter list. Parentheses can be omitted altogether if the closure is the function's only parameter: // This function takes a closure which receives no input parameters and returns an integer, // evaluates it, and uses the closure's return value (an Int) as the function's return value. func foo(closure bar: () -> Int) -> Int { return bar() } // Without trailing closure syntax: foo(closure: { return 1 }) // With trailing closure syntax, and implicit return: foo { 1 } Starting from version 5.3, Swift supports multiple trailing closures: // This function passes the return of the first closure as the parameter of the second, // and returns the second closure's result: func foo(bar: () -> Int, baz: (Int) -> Int) -> Int { return baz(bar()) } // With no trailing closures: foo(bar: { return 1 }, baz: { x in return x + 1 }) // With 1 trailing closure: foo(bar: { return 1 }) { x in return x + 1 } // With 2 trailing closures (only the first closure's argument name is omitted): foo { return 1 } baz: { x in return x + 1 } Swift will provide shorthand argument names for inline closures, removing the need to explicitly name all of the closures parameters. Arguments can be referred to with the names $0, $1, $2, and so on: let names = [\"Josephine\", \"Steve\", \"Chris\", \"Barbara\"] // filter calls the given closure for each value in names. // Values with a character count less than 6 are kept, the others are dropped. let shortNames = names.filter { $0.count Closures may capture values from their surrounding scope. The closure will refer to this captured value for as long as the closure exists: func makeMultiplier(withMultiple multiple: Int) -> (Int) -> (Int) { // Create and return a closure that takes in an Int and returns the input multiplied by the value of multiple. return { $0 * multiple } } let multiplier = makeMultiplier(withMultiple: 3) print(multiplier(3)) // Prints \"9\" print(multiplier(10)) // Prints \"30\" var someString = \"Hello,\" someString += \" world!\" String interpolation allows for the creation of a new string from other values and expressions. Values written between parentheses preceded by a will be inserted into the enclosing string literal: var currentScore = 980 print(\"Your score is \\(currentScore).\") // Prints \"Your score is 980.\" A for-in loop can be used to iterate over the characters contained in a string: for character in \"Swift\" { print(character) } // S // w // i // f // t If the Foundation framework is imported, Swift invisibly bridges the String type to NSString (the String class commonly used in Objective-C). let myValue = anOptionalInstance!.someMethod() In this case, the ! operator unwraps anOptionalInstance to expose the instance inside, allowing the method call to be made on it. If anOptionalInstance is nil, a null-pointer error occurs, terminating the program. This is known as force unwrapping. Optionals may be safely unwrapped using optional chaining, which first tests whether the instance is nil, and then unwraps it if it is not: let myValue = anOptionalInstance?.someMethod() In this case the runtime calls someMethod only if anOptionalInstance is not nil, suppressing the error. A ? must be placed after every optional property. If any of these properties are nil the entire expression evaluates as nil. The origin of the term chaining comes from the more common case where several method calls/getters are chained together. For instance: let aTenant = aBuilding.tenantList[5] let theirLease = aTenant.leaseDetails let leaseStart = theirLease?.startDate can be reduced to: let leaseStart = aBuilding.tenantList[5].leaseDetails?.startDate Swift's use of optionals allows the compiler to use static dispatch because the unwrapping action is called on a defined instance (the wrapper), versus occurring in a runtime dispatch system. Extensions are declared with the extension keyword. struct Rectangle { let width: Double let height: Double } extension Rectangle { var area: Double { return height * width } } // Define a protocol named Printable protocol Printable { var description: String { get } // A read-only property requirement func printDetails() // A method requirement } This protocol can now be adopted by other types: // Adopt the Printable protocol in a class class MyClass: Printable { var description: String { return \"An instance of MyClass\" } func printDetails() { print(description) } } Extensions can be used to add protocol conformance to types. Protocols themselves can also be extended to provide default implementations of their requirements. Adopters may define their own implementations, or they may use the default implementation: extension Printable { // All Printable instances will receive this implementation, or they may define their own. func printDetails() { print(description) } } // Bool now conforms to Printable, and inherits the printDetails() implementation above. extension Bool: Printable { var description: String { return \"An instance of Bool with value: \\(self)\" } } In Swift, like many modern languages supporting interfaces, protocols can be used as types, which means variables and methods can be defined by protocol instead of their specific type: func getSomethingPrintable() -> any Printable { return true } var someSortOfPrintableInstance = getSomethingPrintable() print(someSortOfPrintableInstance.description) // Prints \"An instance of Bool with value: true\" It does not matter what concrete type of someSortOfPrintableInstance is, the compiler will ensure that it conforms to the protocol and thus this code is safe. This syntax also means that collections can be based on protocols also, like let printableArray = [any Printable] . Both extensions and protocols are used extensively in Swift's standard library; in Swift 5.9, approximately 1.2 percent of all symbols within the standard library were protocols, and another 12.3 percent were protocol requirements or default implementations. For instance, Swift uses extensions to add the Equatable protocol to many of their basic types, like Strings and Arrays, allowing them to be compared with the == operator. The Equatable protocol also defines this default implementation: func != (lhs: T, rhs: T) -> Bool This function defines a method that works on any instance conforming to Equatable , providing a not equals operator. Any instance, class or struct, automatically gains this implementation simply by conforming to Equatable . Protocols, extensions, and generics can be combined to create sophisticated APIs. For example, constraints allow types to conditionally adopt protocols or methods based on the characteristics of the adopting type. A common use case may be adding a method on collection types only when the elements contained within the collection are Equatable : extension Array where Element: Equatable { // allEqual will be available only on instances of Array that contain Equatable elements. func allEqual() -> Bool { for element in self { if element != self.first { return false } } return true } } Swift 5.5 introduced structured concurrency into the language. Structured concurrency uses Async/await syntax similar to Kotlin, JavaScript, and Rust. An async function is defined with the async keyword after the parameter list. When calling an async function the await keyword must be written before the function to indicate that execution will potentially suspend while calling function. While a function is suspended the program may run some other concurrent function in the same program. This syntax allows programs to clearly call out potential suspension points and avoid a version of the Pyramid of Doom caused by the previously widespread use of closure callbacks. func downloadText(name: String) async -> String { let result = // ... some asynchronous downloading code ... return result } let text = await downloadText(\"text1\") The async let syntax allows multiple functions to run in parallel. await is again used to mark the point at which the program will suspend to wait for the completion of the async functions called earlier. // Each of these calls to downloadText will run in parallel. async let text1 = downloadText(name: \"text1\") async let text2 = downloadText(name: \"text2\") async let text3 = downloadText(name: \"text3\") let textToPrint = await [text1, text2, text3] // Suspends until all three downloadText calls have returned. print(textToPrint) Tasks and TaskGroups can be created explicitly to create a dynamic number of child tasks during runtime: let taskHandle = Task { await downloadText(name: \"someText\") } let result = await taskHandle.value Swift uses the Actor model to isolate mutable state, allowing different tasks to mutate shared state in a safe manner. Actors are declared with the actor keyword and are reference types, like classes. Only one task may access the mutable state of an actor at the same time. Actors may access and mutate their own internal state freely, but code running in separate tasks must mark each access with the await keyword to indicate that the code may suspend until other tasks finish accessing the actor's state. actor Directory { var names: [String] = [] func add(name: String) { names.append(name) } } let directory = Directory() // Code suspends until other tasks finish accessing the actor. await directory.add(name: \"Tucker\") print(await directory.names) A closure within a class can also create a strong reference cycle by capturing self references. Self references to be treated as weak or unowned can be indicated using a capture list. class Person { let name: String weak var home: Home? // Defined as a weak reference in order to break the reference cycle. weak references do not increment the reference count of the instance that they refer to. init(name: String) { self.name = name } deinit { print(\"De-initialized \\(name)\") } } class Home { let address: String var owner: Person? init(address: String, owner: Person?) { self.address = address self.owner = owner } deinit { print(\"De-initialized \\(address)\") } } var stacy: Person? = Person(name: \"Stacy\") var house21b: Home? = Home(address: \"21b Baker Street\", owner: stacy) stacy?.home = house21b // stacy and house42b now refer to each other. stacy = nil // The reference count for stacy is now 1, because house21b is still holding a reference to it. house21b = nil // house21b's reference count drops to 0, which in turn drops stacy's count to 0 because house21b was the last instance holding a strong reference to stacy. // Prints: // De-initialized 21b Baker Street // De-initialized Stacy Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new identity operator, === , is provided to check if two data elements refer to the same object. Control statements while , if , and switch are similar, but have extended functions, e.g., a switch that takes non-integer cases, while and if supporting pattern matching and conditionally unwrapping optionals, for uses the syntax. Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them. It also has similarities to Objective-C: Basic numeric types: Int, UInt, Float, Double Class methods are inherited, like instance methods; self in class methods is the class the method was called on. Similar for ... in enumeration syntax. Differences from Objective-C include: Statements need not end with semicolons ( ; ), though these must be used to allow more than one statement on one line. No header files. Uses type inference. Generic programming. Functions are first-class objects. Enumeration cases can have associated data (algebraic data types). Operators can be redefined for classes (operator overloading), and new operators can be defined. Strings fully support Unicode. Most Unicode characters can be used in either identifiers or operators. No exception handling. Swift 2 introduces a different and incompatible error-handling model. Several features of earlier C-family languages that are easy to misuse have been removed: Pointers are not exposed by default. There is no need for the programmer to keep track of and mark names for referencing or dereferencing. Assignments return no value. This prevents the common error of writing i = 0 instead of i == 0 (which throws a compile-time error). No need to use break statements in switch blocks. Individual cases do not fall through to the next case unless the fallthrough statement is used. Variables and constants are always initialized and array bounds are always checked. Integer overflows, which result in undefined behavior for signed integers in C, are trapped as a run-time error in Swift. Programmers can choose to allow overflows by using the special arithmetical operators &+ , &- , &* , &/ and &% . The properties min and max are defined in Swift for all integer types and can be used to safely check for potential overflows, versus relying on constants defined for each type in external libraries. The one-statement form of if and while , which allows for the omission of braces around the statement, is unsupported. C-style enumeration for (int i = 0; i , which is prone to off-by-one errors, is unsupported (from Swift 3 onward). The pre- and post- increment and decrement operators ( i++ , --i ...) are unsupported (from Swift 3 onward), more so since C-style for statements are also unsupported from Swift 3 onward.",
  "categories": [
    "109372261",
    "109563975",
    "11060667",
    "20161863",
    "22912281",
    "22928584",
    "23118434",
    "23204648",
    "23284516",
    "23603337",
    "24153113",
    "24165216",
    "24623845",
    "24769764",
    "26814237",
    "26814240",
    "27320558",
    "27367243",
    "27383506",
    "3926236",
    "43907796",
    "50998678",
    "65710263"
  ],
  "license": "CC BY-SA 4.0",
  "source_uri": "https://en.wikipedia.org/w/index.php?oldid=1379000016",
  "content_hash": "",
  "created_at": null,
  "updated_at": 1791354728.0,
  "claims": [
    {
      "id": 32415407,
      "subject_qid": "",
      "subject_slug": "swift-programming-language",
      "predicate": "release date",
      "object_text": "2014",
      "object_num": 20140000.0,
      "object_unit": null,
      "polarity": 1,
      "qualifier": "",
      "source_uri": "https://en.wikipedia.org/w/index.php?oldid=1379000016",
      "source_name": "Wikipedia",
      "source_tier": 3,
      "retrieved_at": 1792516217.7613254,
      "confidence": 0.95,
      "article_slug": "swift-programming-language",
      "span_start": 16,
      "span_end": 64
    }
  ],
  "contradictions": [],
  "confidence": 0.95,
  "csl": {
    "id": "enwiki-001379000016",
    "type": "webpage",
    "title": "Swift (programming language)",
    "author": [
      {
        "family": "Anticloud FZ LLE",
        "literal": "Anticloud FZ LLE"
      }
    ],
    "container-title": "encyclopegia.org",
    "publisher": "Anticloud FZ LLE",
    "publisher-place": "Dubai, United Arab Emirates",
    "URL": "https://encyclopegia.org/a/swift-programming-language",
    "issued": {
      "date-parts": [
        [
          2026,
          11,
          19
        ]
      ]
    },
    "accessed": {
      "date-parts": [
        [
          2026,
          11,
          19
        ]
      ]
    },
    "license": "CC BY-SA 4.0",
    "DOI": "eo1:enwiki-001379000016",
    "isBasedOn": "https://en.wikipedia.org/w/index.php?oldid=1379000016",
    "note": "Immutable snapshot enwiki-001379000016"
  }
}