History
Development of Swift started in July 2010 byPlatforms
The platforms Swift supports are Apple's operating systems (Version history
Features
Swift is an alternative to the Objective-C language that employs modern programming-language theory concepts and strives to present a simpler syntax. During its introduction, it was described simply as "Objective-C without the baggage of C". By default, Swift does not expose pointers and other unsafe accessors, in contrast to Objective-C, which uses pointers pervasively to refer to object instances. Also, Objective-C's use of aClosure support
Swift supports closures (known as lambdas in other languages). Closures are self-contained blocks of functionality that can be passed around and used in code, and can also be used asguard
statement.
String support
Under the+
operator, allowing greatly simplified syntax; the prior example becoming:
Access control
Swift supports fiveOptionals and chaining
An important new feature in Swift is option types, which allowOptional
mechanism—to make an Integer that is nullable, one would use a declaration similar to var optionalInteger: Optional
. As in C#, Swift also includes syntactic sugar for this, allowing one to indicate a variable is optional by placing a question mark after the type name, var optionalInteger: Int?
. Variables or constants that are marked optional either have a value of the underlying type or are nil
. Optional types ''wrap'' the base type, resulting in a different instance. String
and String?
are fundamentally different types, the latter has more in common with Int?
than String
.
To access the value inside, assuming it is not nil, it must be ''unwrapped'' to expose the instance inside. This is performed with the !
operator:
!
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. This can be annoying in practice, so Swift also includes the concept of optional chaining to test whether the instance is nil and then unwrap it if it is non-null:
someMethod
only if anOptionalInstance
is not nil, suppressing the error. Normally this requires the programmer to test whether myValue
is nil before proceeding. The origin of the term ''chaining'' comes from the more common case where several method calls/getters are chained together. For instance:
?
syntax circumvents the guard
for cases in which code should stop executing if some condition is unmet:
guard
has three benefits. While the syntax can act as an if
statement, its primary benefit is inferring non-nullability. Where an if
statement requires a case, guard
assumes the case based on the condition provided. Also, since guard
contains no scope, with exception of the else
closure, leaseStart
is presented as an unwrapped optional to the guard's super-scope. Lastly, if the guard
statement's test fails, Swift requires the else
to exit the current method or loop, ensuring leaseStart
never is accessed when nil
. This is performed with the keywords return
, continue
, break
, or throw
, or by calling a function returning a Never
(e.g. fatalError()
).
Objective-C was weakly typed and allowed any method to be called on any object at any time. If the method call failed, there was a default handler in the runtime that returned nil. That meant that no unwrapping or testing was needed, the equivalent statement in Objective-C:
Value types
In many object-oriented languages, objects are represented internally in two parts. The object is stored as a block of data placed on theclass
declaration and the latter using struct
. Structs in Swift have almost all the same features as classes: methods, implementing protocols and using the extension mechanisms. For this reason, Apple terms all data generically as ''instances'', versus objects or values. Structs do not support inheritance, however.
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 dereference. The performance improvement inherent to the pass-by-value concept is such that Swift uses these types for almost all common data types, including Int
and Double
, and types normally represented by objects, like String
and Array
. Using value types can result in significant performance improvements in user applications as well.
To ensure that even the largest structs do not cause a performance penalty when they are handed off, Swift uses copy on write so that the objects are copied only if and when the program attempts to change a value in them. This means that the various accessors have what is in effect a pointer to the same data storage. So while the data is physically stored as one instance in memory, at the level of the application, these values are separate and physical separation is enforced by copy on write only if needed.
Protocol-oriented programming
A key feature of Objective-C is its support for ''categories'', methods that can be added to extend classes at runtime. Categories allow extending classes in-place to add new functions with no need to subclass or even have access to the original source code. An example might be to addNSString
class, which means all instances of NSString in the application gain spell checking. The system is also widely used as an organizational technique, allowing related code to be gathered into library-like extensions. Swift continues to support this concept, although they are now termed ''extensions'', and declared with the keyword extension
. Unlike Objective-C, Swift can also add new properties accessors, types, and enums to extant instances .
Another key feature of Objective-C is its use of ''protocols'', known in most modern languages as ''interfaces''. Protocols promise that a particular class implements a set of methods, meaning that other objects in the system can call those methods on any object supporting that protocol. This is often used in modern OO languages as a substitute for multiple inheritance, although the feature sets are not entirely similar. A common example of a protocol in Cocoa is the NSCopying
protocol, which defines one method, copyWithZone
, that implements deep copying on objects.
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. 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.
For example, a protocol might be declared called StringConvertible
, which ensures that instances that conform to the protocol implement a toString
method that returns a String
. In Swift, this can be declared with code like this:
someSortOfPrintableObject
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 = tringConvertible/code>.
As Swift treats structs and classes as similar concepts, both extensions and protocols are extensively used in Swift's runtime to provide a rich API based on structs. For instance, Swift uses an extension to add the Equatable
protocol to many of their basic types, like Strings and Arrays, allowing them to be compared with the
operator. A concrete example of how all of these features interact can be seen in the concept of ''default protocol implementations'':
func !=(lhs: T, rhs: T) -> Bool
This function defines a method that works on any instance conforming to Equatable
, providing a ''not equals'' function. Any instance, class or struct, automatically gains this implementation simply by conforming to Equatable
. As many instances gain Equatable
through their base implementations or other generic extensions, most basic objects in the runtime gain equals and not equals with no code.
This combination of protocols, defaults, protocol inheritance, and extensions allows many of the functions normally associated with classes and inheritance to be implemented on value types. Properly used, this can lead to dramatic performance improvements with no significant limits in API. This concept is so widely used within Swift that Apple has begun calling it a ''protocol-oriented programming language''. They suggest addressing many of the problem domains normally solved through classes and inheritance using protocols and structs instead.
Libraries, runtime and development
On 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. Swift and Objective-C code can be used in one program, and by extension, C and C++ also. In contrast to C, C++ code cannot be used directly from Swift. An Objective-C or C wrapper must be created between Swift and C++. 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. The converse is not true: a Swift class cannot be subclassed in Objective-C.
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 #import "MyApp-Swift.h"
. Not all symbols are available through this mechanism, however—use of Swift-specific features like generic types, non-object optional types, sophisticated enums, or even Unicode identifiers may render a symbol inaccessible from Objective-C.
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 @
syntax, but the currently available set is small. One example is the @IBOutlet
attribute, which marks a given value in the code as an ''outlet'', available for use within Interface Builder (IB). An ''outlet'' is a device that binds the value of the on-screen display to an object in code.
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.
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.
Memory management
Swift uses Automatic Reference Counting (ARC) to manage memory. Apple used to require manual memory management in Objective-C, but introduced ARC in 2011 to allow for easier memory allocation and deallocation. One problem with ARC is the possibility of creating a '' strong reference cycle'', where objects reference each other in a way that you can reach the object you started from by following references (e.g. A references B, B references A). This causes them to become leaked into memory as they are never released. Swift provides the keywords weak
and unowned
to prevent strong reference cycles. Typically a parent-child relationship would use a strong reference while a child-parent would use either weak
reference, where parents and children can be unrelated, or unowned
where a child always has a parent, but parent may not have a child. Weak references must be optional variables, since they can change and become nil
.
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.''
Debugging and other elements
A 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 Systems programming, or system programming, is the activity of programming computer system software. The primary distinguishing characteristic of systems programming when compared to application programming is that application programming aims to pr ...
languages. The REPL is further enhanced with playgrounds, interactive views running within the Xcode environment that respond to code or debugger changes on-the-fly. Playgrounds allow programmers to add in Swift code along with markdown documentation. If some code changes over time or with regard to some other ranged input value, the view can be used with the Timeline Assistant to demonstrate the output in an animated way. In addition, Xcode has debugging features for Swift development including breakpoints, step through and step over statements, as well as UI element placement breakdowns for app developers.
Apple says that Swift is "an industrial-quality programming language that's as expressive and enjoyable as a scripting language".
Performance
Many of the features introduced with Swift have well-known performance and safety trade-offs. Apple has implemented optimizations that reduce this overhead.
Comparisons to other languages
Swift is considered a C family programming language and is similar to C in various ways:
* Most C operators are used in Swift, but there are some new operators, for example to support integer operations with overflow (see under differences).
* Curly braces are used to group statements.
* 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
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ai ...
.
* 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
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
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 do not need to end with semicolons (;
), though these must be used to allow more than one statement on a 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
by throwing 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 < c; i++)
, which is prone to off-by-one errors, is unsupported (from Swift 3 onward).
** The pre- and post- increment and decrement operators
Increment and decrement operators are unary operators that ''add'' or ''subtract'' one, to or from their operand, respectively.
They are commonly implemented in imperative programming languages. C-like languages feature two versions (pre- an ...
(i++
, --i
...) are unsupported (from Swift 3 onward), more so since C-style for
statements are also unsupported from Swift 3 onward.
Development and other implementations
Since the language is open-source, there are prospects of it being ported to the web. Some web frameworks have already been developed, such as IBM's Kitura, Perfect
Perfect commonly refers to:
* Perfection, completeness, excellence
* Perfect (grammar), a grammatical category in some languages
Perfect may also refer to:
Film
* Perfect (1985 film), ''Perfect'' (1985 film), a romantic drama
* Perfect (2018 f ...
and Vapor.
An official "Server APIs" work group has also been started by Apple, with members of the Swift developer community playing a central role.
A second free implementation of Swift that targets Cocoa
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
, Microsoft's Common Language Infrastructure
The Common Language Infrastructure (CLI) is an open specification and technical standard originally developed by Microsoft and standardized by ISO/IEC (ISO/IEC 23271) and Ecma International (ECMA 335) that describes executable code and a runt ...
( .NET), and the Java and Android
Android may refer to:
Science and technology
* Android (robot), a humanoid robot or synthetic organism designed to imitate a human
* Android (operating system), Google's mobile operating system
** Bugdroid, a Google mascot sometimes referred to ...
platform exists as part of the ''Elements Compiler'' from RemObjects Software.
By combining toolchains from LLVM and Macintosh Programmer's Workshop, it is possible to run a very small subset of the language on Mac OS 9
Mac OS 9 is the ninth major release of Apple Inc., Apple's classic Mac OS operating system which was succeeded by macOS, Mac OS X (renamed to OS X in 2011 and macOS in 2016) in 2001. Introduced on October 23, 1999, it was promoted by Apple as "T ...
.
See also
* Comparison of programming languages
* Objective-C
* Kotlin (programming language)
* Python (programming language)
* Nim (programming language)
References
External links
*
Swift
at Apple Developer
*
Swift Example
Server-side Swift - The Vapor Framework
{{Authority control
Apple Inc. software
Computer-related introductions in 2014
Object-oriented programming languages
Pattern matching programming languages
Programming languages
Programming languages created in 2014
Software using the Apache license
Statically typed programming languages
Systems programming languages
Declarative programming