Swift (programming language)
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[11] 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"[12] (similar to traits and type classes).[13] Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC).[14] 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.[15][16] Through version 3.0 the syntax of Swift went through significant evolution, with the core team making source stability a focus in later versions.[17][18] In the first quarter of 2018 Swift surpassed Objective-C in measured popularity.[19] Swift 4.0, released in 2017, introduced several changes to some built-in classes and structures. Code written with previous versions of Swift can be updated using the migration functionality built into Xcode. Swift 5, released in March 2019, introduced a stable binary interface on Apple platforms, allowing the Swift runtime to be incorporated into Apple operating systems. It is source compatible with Swift 4.[20] Swift 5.1 was officially released in September 2019. Swift 5.1 builds on the previous version of Swift 5 by extending the stable features of the language to compile-time with the introduction of module stability. The introduction of module stability makes it possible to create and share binary frameworks that will work with future releases of Swift.[21] Swift 5.5, officially announced by Apple at the 2021 WWDC, significantly expands language support for concurrency and asynchronous code, notably introducing a unique version of the actor model.[22] Swift 5.9, was released in September 2023 and includes a macro system, generic parameter packs, and ownership features like the new Swift 5.10, was released in March 2024. This version improves the language's concurrency model, allowing for full data isolation to prevent data races. It is also the last release before Swift 6.[24] Version 5.10 is currently available for macOS, Windows and for Linux.[25] Swift 6 was released in September 2024.[26] Swift 6.1 was released in March 2025. Which included "new language enhancements to improve productivity, diagnostics improvements, package traits, and ongoing work to improve data-race safety usability and compile times."[27] HistoryDevelopment of Swift started in July 2010 by Chris Lattner, with the eventual collaboration of many other programmers at Apple. Swift was motivated by the need for a replacement for Apple's earlier programming language Objective-C, which had been largely unchanged since the early 1980s and lacked modern language features. Swift took language ideas "from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list".[7] On June 2, 2014, the Apple Worldwide Developers Conference (WWDC) application became the first publicly released app written with Swift.[28] A beta version of the programming language was released to registered Apple developers at the conference, but the company did not promise that the final version of Swift would be source code compatible with the test version. Apple planned to make source code converters available if needed for the full release.[28] The Swift Programming Language, a free 500-page manual, was also released at WWDC, and is available on the Apple Books Store and the official website.[29] Swift reached the 1.0 milestone on September 9, 2014, with the Gold Master of Xcode 6.0 for iOS.[30] Swift 1.1 was released on October 22, 2014, alongside the launch of Xcode 6.1.[31] Swift 1.2 was released on April 8, 2015, along with Xcode 6.3.[32] Swift 2.0 was announced at WWDC 2015, and was made available for publishing apps in the App Store on September 21, 2015.[33] Swift 3.0 was released on September 13, 2016.[34] Swift 4.0 was released on September 19, 2017.[35] Swift 4.1 was released on March 29, 2018.[36] Swift won first place for Most Loved Programming Language in the Stack Overflow Developer Survey 2015[37] and second place in 2016.[38] On December 3, 2015, the Swift language, supporting libraries, debugger, and package manager were open-sourced under the Apache 2.0 license with a Runtime Library Exception,[39] and Swift.org was created to host the project. The source code is hosted on GitHub, where it is easy for anyone to get the code, build it themselves, and even create pull requests to contribute code back to the project. In December 2015, IBM announced its Swift Sandbox website, which allows developers to write Swift code in one pane and display output in another.[40][41][42] The Swift Sandbox was deprecated in January 2018.[43] During the WWDC 2016, Apple announced an iPad exclusive app, named Swift Playgrounds, intended to teach people how to code in Swift. The app is presented in a 3D video game-like interface which provides feedback when lines of code are placed in a certain order and executed.[44][45][46] In January 2017, Chris Lattner announced his departure from Apple for a new position with Tesla Motors, with the Swift project lead role going to team veteran Ted Kremenek.[47][48] During WWDC 2019, Apple announced SwiftUI with Xcode 11, which provides a framework for declarative UI structure design across all Apple platforms.[49] Official downloads of the SDK and toolchain for the Ubuntu distribution of Linux have been available since Swift 2.2, with more distros added since Swift 5.2.4, CentOS and Amazon Linux.[50] There is an unofficial SDK and native toolchain package for Android too.[51][52] PlatformsThe platforms Swift supports are Apple's operating systems (Darwin, iOS, iPadOS, macOS, tvOS, watchOS), Linux, Windows, and Android.[53][54] A key aspect of Swift's design is its ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades, such as Cocoa and the Cocoa Touch frameworks. On Apple platforms,[55] it links with the Objective-C runtime library, which allows C, Objective-C, C++ and Swift code to run within one program.[56] Version history
Features
Swift is a general purpose programming language that employs modern programming-language theory concepts and strives to present a simple, yet powerful syntax. Swift incorporates innovations and conventions from various programming languages, with notable inspiration from Objective-C, which it replaced as the primary development language on Apple Platforms. Swift was designed to be safe and friendly to new programmers while not sacrificing speed. By default Swift manages all memory automatically and ensures variables are always initialized before use. Array accesses are checked for out-of-bounds errors and integer operations are checked for overflow. Parameter names allow creating clear APIs. Protocols define interfaces that types may adopt, while extensions allow developers to add more function to existing types. Swift enables object-oriented programming with the support for classes, subtyping, and method overriding. Optionals allow nil values to be handled explicitly and safely. Concurrent programs can be written using async/await syntax, and actors isolate shared mutable state in order to eliminate data races.[74][75] Basic syntaxSwift's syntax is similar to C-style languages. Code begins executing in the global scope by default.[76] Alternatively, the Swift's "Hello, World!" program is: print("Hello, world!")
The 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 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 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"
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."
let someNumber = 42
switch someNumber {
case ..<0:
print("\(someNumber) negative.")
case 0:
print("\(someNumber) is 0.")
case 1...9:
print("\(someNumber) greater than 0, but less than 10.")
default:
print("\(someNumber) is greater than 9.")
}
// Prints "42 is greater than 9."
let names = ["Will", "Anna", "Bart"]
for name in names {
print(name)
}
// Prints:
// Will
// Anna
// Bart
// Add together all the numbers from 1 to 5.
var i = 1
var result = 0
while i <= 5 { // The loop performs its body as long as i is less than or equal to 5.
result += i // Add i to the current result.
i += 1 // Increment i by 1.
}
print(result) // Prints "15"
Closure supportSwift supports closures, which are self-contained blocks of functionality that can be passed around and used in code,[78] and can also be used as anonymous functions. Here are some examples: // 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 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:[79] // 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.[80] 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 < 6 }
print(shortNames) // Prints "["Steve", "Chris"]"
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"
String supportThe Swift standard library includes unicode-compliant 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 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). Callable objectsIn Swift, callable objects are defined using struct CallableStruct {
var value: Int
func callAsFunction(_ number: Int, scale: Int) {
print(scale * (number + value))
}
}
let callable = CallableStruct(value: 100)
callable(4, scale: 2)
callable.callAsFunction(4, scale: 2)
// Both function calls print 208.
Access controlSwift supports five access control levels for symbols: Optionals and chainingAn important feature in Swift is option types, which allow references or values to operate in a manner similar to the common pattern in C, where a pointer may either refer to a specific value or no value at all. This implies that non-optional types cannot result in a null-pointer error; the compiler can ensure this is not possible. Optional types are created with the To access the value inside, assuming it is not nil, it must be unwrapped to expose the instance inside. This is performed with the let myValue = anOptionalInstance!.someMethod()
In this case, the let myValue = anOptionalInstance?.someMethod()
In this case the runtime calls 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. Value typesIn many object-oriented languages, objects are represented internally in two parts. The object is stored as a block of data placed on the heap, while the name (or "handle") to that object is represented by a pointer. Objects are passed between methods by copying the value of the pointer, allowing the same underlying data on the heap to be accessed by anyone with a copy. In contrast, basic types like integers and floating-point values are represented directly; the handle contains the data, not a pointer to it, and that data is passed directly to methods by copying. These styles of access are termed pass-by-reference in the case of objects, and pass-by-value for basic types. Both concepts have their advantages and disadvantages. Objects are useful when the data is large, like the description of a window or the contents of a document. In these cases, access to that data is provided by copying a 32- or 64-bit value, versus copying an entire data structure. However, smaller values like integers are the same size as pointers (typically both are one word), so there is no advantage to passing a pointer, versus passing the value. Swift offers built-in support for objects using either pass-by-reference or pass-by-value semantics, the former using the The programmer is free to choose which semantics are more appropriate for each data structure in the application. Larger structures like windows would be defined as classes, allowing them to be passed around as pointers. Smaller structures, like a 2D point, can be defined as structs, which will be pass-by-value and allow direct access to their internal data with no indirection or reference counting. The performance improvement inherent to the pass-by-value concept is such that Swift uses these types for almost all common data types, including
ExtensionsExtensions add new functionality to an existing type, without the need to subclass or even have access to the original source code. Extensions can add new methods, initializers, computed properties, subscripts, and protocol conformances.[89] An example might be to add a spell checker to the base
Extensions are declared with the struct Rectangle {
let width: Double
let height: Double
}
extension Rectangle {
var area: Double {
return height * width
}
}
Protocol-oriented programmingProtocols promise that a particular type implements a set of methods or properties, meaning that other instances in the system can call those methods on any instance implementing that protocol. This is often used in modern object-oriented languages as a substitute for multiple inheritance, although the feature sets are not entirely similar. In Objective-C, and most other languages implementing the protocol concept, it is up to the programmer to ensure that the required methods are implemented in each class.[90] Swift adds the ability to add these methods using extensions, and to use generic programming (generics) to implement them. Combined, these allow protocols to be written once and support a wide variety of instances. Also, the extension mechanism can be used to add protocol conformance to an object that does not list that protocol in its definition.[91] For example, a protocol might be declared called // 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 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.[92] For instance, Swift uses extensions to add the func !=<T : Equatable>(lhs: T, rhs: T) -> Bool
This function defines a method that works on any instance conforming to
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 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
}
}
Concurrency
Swift 5.5 introduced structured concurrency into the language.[94] Structured concurrency uses Async/await syntax similar to Kotlin, JavaScript, and Rust. An async function is defined with the func downloadText(name: String) async -> String {
let result = // ... some asynchronous downloading code ...
return result
}
let text = await downloadText("text1")
The // 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 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)
Libraries, runtime, developmentOn Apple systems, Swift uses the same runtime as the extant Objective-C system, but requires iOS 7 or macOS 10.9 or higher. It also depends on Grand Central Dispatch.[96] Swift and Objective-C code can be used in one program, and by extension, C and C++ also. Beginning in Swift 5.9, C++ code can be used directly from Swift code.[97] In the case of Objective-C, Swift has considerable access to the object model, and can be used to subclass, extend and use Objective-C code to provide protocol support.[98] The converse is not true: a Swift class cannot be subclassed in Objective-C.[99] To aid development of such programs, and the re-use of extant code, Xcode 6 and higher offers a semi-automated system that builds and maintains a bridging header to expose Objective-C code to Swift. This takes the form of an additional header file that simply defines or imports all of the Objective-C symbols that are needed by the project's Swift code. At that point, Swift can refer to the types, functions, and variables declared in those imports as though they were written in Swift. Objective-C code can also use Swift code directly, by importing an automatically maintained header file with Objective-C declarations of the project's Swift symbols. For instance, an Objective-C file in a mixed project called "MyApp" could access Swift classes or functions with the code Swift also has limited support for attributes, metadata that is read by the development environment, and is not necessarily part of the compiled code. Like Objective-C, attributes use the On non-Apple systems, Swift does not depend on an Objective-C runtime or other Apple system libraries; a set of Swift "Corelib" implementations replace them. These include a "swift-corelibs-foundation" to stand in for the Foundation Kit, a "swift-corelibs-libdispatch" to stand in for the Grand Central Dispatch, and an "swift-corelibs-xctest" to stand in for the XCTest APIs from Xcode.[101] As of 2019, with Xcode 11, Apple has also added a major new UI paradigm called SwiftUI. SwiftUI replaces the older Interface Builder paradigm with a new declarative development paradigm.[102] Memory managementSwift uses Automatic Reference Counting (ARC) to manage memory. Every instance of a class or closure maintains a reference count which keeps a running tally of the number of references the program is holding on to. When this count reaches 0 the instance is deallocated. This automatic deallocation removes the need for a garbage collector as instances are deallocated as soon as they are no longer needed. A strong reference cycle can occur if two instances each strongly reference each other (e.g. A references B, B references A). Since neither instances reference count can ever reach zero neither is ever deallocated, resulting in a memory leak. Swift provides the keywords 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
DebuggingA key element of the Swift system is its ability to be cleanly debugged and run within the development environment, using a read–eval–print loop (REPL), giving it interactive properties more in common with the scripting abilities of Python than traditional system programming languages. The REPL is further enhanced with playgrounds, interactive views running within the Xcode environment or Playgrounds app that respond to code or debugger changes on-the-fly.[104] Playgrounds allow programmers to add in Swift code along with markdown documentation. Programmers can step through code and add breakpoints using LLDB either in a console or an IDE like Xcode. Comparisons to other languagesSwift is considered a C family programming language and is similar to C in various ways:
It also has similarities to Objective-C:
Differences from Objective-C include:
Development and other implementationsBecause Swift can run on Linux, it is sometimes also used as a server-side language.[108] Some web frameworks have been developed, such as IBM's Kitura (now discontinued), Perfect, Vapor, and Hummingbird. An official "Server APIs" work group has also been started by Apple,[109] with members of the Swift developer community playing a central role.[110] A second free implementation of Swift that targets Cocoa, Microsoft's Common Language Infrastructure (.NET Framework, now .NET), and the Java and Android platform exists as part of the Elements Compiler from RemObjects Software.[111] Subsets of Swift have been ported to additional platforms, such as Arduino[112] and Mac OS 9.[113] See also
References
External links |
Portal di Ensiklopedia Dunia