title: Go (programming language)

paragraphs: Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency. The language is often referred to as Golang because of its domain name, codice_1, but the proper name is Go.

paragraphs: A third-party transpiler GopherJS compiles Go to JavaScript for front-end web development.

paragraphs: Go was designed at Google in 2007 to improve programming productivity in an era of multicore, networked machines and large codebases. The designers wanted to address criticism of other languages in use at Google, but keep their useful characteristics:

paragraphs: The designers were primarily motivated by their shared dislike of C++.

paragraphs: Go was publicly announced in November 2009, and version 1.0 was released in March 2012. Go is widely used in production at Google and in many other organizations and open-source projects.

paragraphs: In November 2016, the Go and Go Mono fonts were released by type designers Charles Bigelow and Kris Holmes specifically for use by the Go project. Go is a humanist sans-serif which resembles Lucida Grande and Go Mono is monospaced. Each of the fonts adhere to the WGL4 character set and were designed to be legible with a large x-height and distinct letterforms. Both Go and Go Mono adhere to the DIN 1450 standard by having a slashed zero, lowercase codice_2 with a tail, and an uppercase codice_3 with serifs.

paragraphs: In April 2018, the original logo was replaced with a stylized GO slanting right with trailing streamlines. However, the Gopher mascot remained the same.

paragraphs: In August 2018, the Go principal contributors published two "draft designs" for new language features, generics and error handling, and asked Go users to submit feedback on them.

paragraphs: Lack of support for generic programming and the verbosity of error handling in Go 1.x had drawn considerable criticism.

paragraphs: Go 1 guarantees compatibility for the language specification and major parts of the standard library. All versions up to the current Go 1.15 release have maintained this promise.

paragraphs: Each major Go release is supported until there are two newer major releases.

paragraphs: Go is influenced by C, but with an emphasis on greater simplicity and safety. The language consists of:

paragraphs: Go's syntax includes changes from C aimed at keeping code concise and readable. A combined declaration/initialization operator was introduced that allows the programmer to write codice_9 or codice_10, without specifying the types of variables used. This contrasts with C's codice_11 and codice_12. Semicolons still terminate statements, but are implicit when the end of a line occurs. Methods may return multiple values, and returning a codice_13 pair is the conventional way a method indicates an error to its caller in Go. Go adds literal syntaxes for initializing struct parameters by name and for initializing maps and slices. As an alternative to C's three-statement codice_14 loop, Go's codice_15 expressions allow concise iteration over arrays, slices, strings, maps, and channels.

paragraphs: Go has a number of built-in types, including numeric ones (, , , etc.), booleans, and character strings (). Strings are immutable; built-in operators and keywords (rather than functions) provide concatenation, comparison, and UTF-8 encoding/decoding. Record types can be defined with the keyword.

paragraphs: For each type and each non-negative integer constant , there is an array type denoted ; arrays of differing lengths are thus of different types. Dynamic arrays are available as "slices", denoted for some type . These have a length and a "capacity" specifying when new memory needs to be allocated to expand the array. Several slices may share their underlying memory.

paragraphs: Pointers are available for all types, and the pointer-to- type is denoted . Address-taking and indirection use the and operators, as in C, or happen implicitly through the method call or attribute access syntax. There is no pointer arithmetic, except via the special type in the standard library.

paragraphs: For a pair of types , , the type is the type of hash tables mapping type- keys to type- values. Hash tables are built into the language, with special syntax and built-in functions. is a "channel" that allows sending values of type "T" between concurrent Go processes.

paragraphs: Aside from its support for interfaces, Go's type system is nominal: the keyword can be used to define a new "named type", which is distinct from other named types that have the same layout (in the case of a , the same members in the same order). Some conversions between types (e.g., between the various integer types) are pre-defined and adding a new type may define additional conversions, but conversions between named types must always be invoked explicitly. For example, the keyword can be used to define a type for IPv4 addresses, based on 32-bit unsigned integers:

paragraphs: With this type definition, interprets the value as an IP address. Simply assigning to a variable of type is a type error.

paragraphs: Constant expressions may be either typed or "untyped"; they are given a type when assigned to a typed variable if the value they represent passes a compile-time check.

paragraphs: Function types are indicated by the keyword; they take zero or more parameters and return zero or more values, all of which are typed. The parameter and return values determine a function type; thus, is the type of functions that take a and a 32-bit signed integer, and return a signed integer (of default width) and a value of the built-in interface type .

paragraphs: Any named type has a method set associated with it. The IP address example above can be extended with a method for checking whether its value is a known standard:

paragraphs: // ZeroBroadcast reports whether addr is 255.255.255.255.

paragraphs: func (addr ipv4addr) ZeroBroadcast() bool {

paragraphs: Due to nominal typing, this method definition adds a method to , but not on . While methods have special definition and call syntax, there is no distinct method type.

paragraphs: Go provides two features that replace class inheritance.

paragraphs: The first is "embedding", which can be viewed as an automated form of composition or delegation.

paragraphs: The second are its "interfaces", which provides runtime polymorphism. Interfaces are a class of types and provide a limited form of structural typing in the otherwise nominal type system of Go. An object which is of an interface type is also of another type, much like C++ objects being simultaneously of a base and derived class. Go interfaces were designed after protocols from the Smalltalk programming language. Multiple sources use the term duck typing when describing Go interfaces. Although the term duck typing is not precisely defined and therefore not wrong, it usually implies that type conformance is not statically checked. Since conformance to a Go interface is checked statically by the Go compiler (except when performing a type assertion), the Go authors prefer the term "structural typing".

paragraphs: The definition of an interface type lists required methods by name and type. Any object of type T for which functions exist matching all the required methods of interface type I is an object of type I as well. The definition of type T need not (and cannot) identify type I. For example, if , are defined as

paragraphs: type Square struct { // Note: no "implements" declaration

paragraphs: type Circle struct { // No "implements" declaration here either

paragraphs: then both a and a are implicitly a and can be assigned to a -typed variable. In formal language, Go's interface system provides structural rather than nominal typing. Interfaces can embed other interfaces with the effect of creating a combined interface that is satisfied by exactly the types that implement the embedded interface and any methods that the newly defined interface adds.

paragraphs: The Go standard library uses interfaces to provide genericity in several places, including the input/output system that is based on the concepts of and .

paragraphs: Besides calling methods via interfaces, Go allows converting interface values to other types with a run-time type check. The language constructs to do so are the "type assertion", which checks against a single potential type, and the "type switch", which checks against multiple types.

paragraphs: The "empty interface" codice_16 is an important base case because it can refer to an item of "any" concrete type. It is similar to the class in Java or C# and is satisfied by any type, including built-in types like . Code using the empty interface cannot simply call methods (or built-in operators) on the referred-to object, but it can store the codice_16 value, try to convert it to a more useful type via a type assertion or type switch, or inspect it with Go's codice_18 package. Because codice_16 can refer to any value, it is a limited way to escape the restrictions of static typing, like codice_20 in C but with additional run-time type checks.

paragraphs: The codice_16 type can be used to model structured data of any arbitrary schema in Go, such as JSON or YAML data, or Terraform resources, by representing it as a codice_22 (map of string to empty interface). This recursively describes data in the form of a dictionary with string keys and values of any type.

paragraphs: Interface values are implemented using pointer to data and a second pointer to run-time type information. Like some other types implemented using pointers in Go, interface values are codice_23 if uninitialized.

paragraphs: In Go's package system, each package has a path (e.g., codice_24 or codice_25) and a name (e.g., codice_26 or codice_27). References to other packages' definitions must "always" be prefixed with the other package's name, and only the "capitalized" names from other packages are accessible: codice_28 is public but codice_29 is not. The codice_7 command can retrieve packages stored in a remote repository and developers are encouraged to develop packages inside a base path corresponding to a source repository (such as example.com/user_name/package_name) to reduce the likelihood of name collision with future additions to the standard library or other external libraries.

paragraphs: Proposals exist to introduce a proper package management solution for Go similar to CPAN for Perl or Rust's cargo system or Node's npm system.

paragraphs: The Go language has built-in facilities, as well as library support, for writing concurrent programs. Concurrency refers not only to CPU parallelism, but also to asynchrony: letting slow operations like a database or network read run while the program does other work, as is common in event-based servers.

paragraphs: The primary concurrency construct is the "goroutine", a type of light-weight process. A function call prefixed with the codice_31 keyword starts a function in a new goroutine. The language specification does not specify how goroutines should be implemented, but current implementations multiplex a Go process's goroutines onto a smaller set of operating-system threads, similar to the scheduling performed in Erlang.

paragraphs: While a standard library package featuring most of the classical concurrency control structures (mutex locks, etc.) is available, idiomatic concurrent programs instead prefer "channels", which provide send messages between goroutines. Optional buffers store messages in FIFO order and allow sending goroutines to proceed before their messages are received.

paragraphs: Channels are typed, so that a channel of type can only be used to transfer messages of type . Special syntax is used to operate on them; is an expression that causes the executing goroutine to block until a value comes in over the channel , while sends the value (possibly blocking until another goroutine receives the value). The built-in -like statement can be used to implement non-blocking communication on multiple channels; see below for an example. Go has a memory model describing how goroutines must use channels or other operations to safely share data.

paragraphs: The existence of channels sets Go apart from actor model-style concurrent languages like Erlang, where messages are addressed directly to actors (corresponding to goroutines). The actor style can be simulated in Go by maintaining a one-to-one correspondence between goroutines and channels, but the language allows multiple goroutines to share a channel or a single goroutine to send and receive on multiple channels.

paragraphs: From these tools one can build concurrent constructs like worker pools, pipelines (in which, say, a file is decompressed and parsed as it downloads), background calls with timeout, "fan-out" parallel calls to a set of services, and others. Channels have also found uses further from the usual notion of interprocess communication, like serving as a concurrency-safe list of recycled buffers, implementing coroutines (which helped inspire the name "goroutine"), and implementing iterators.

paragraphs: Concurrency-related structural conventions of Go (channels and alternative channel inputs) are derived from Tony Hoare's communicating sequential processes model. Unlike previous concurrent programming languages such as Occam or Limbo (a language on which Go co-designer Rob Pike worked), Go does not provide any built-in notion of safe or verifiable concurrency. While the communicating-processes model is favored in Go, it is not the only one: all goroutines in a program share a single address space. This means that mutable objects and pointers can be shared between goroutines; see , below.

paragraphs: Although Go's concurrency features are not aimed primarily at parallel processing, they can be used to program shared-memory multi-processor machines. Various studies have been done into the effectiveness of this approach. One of these studies compared the size (in lines of code) and speed of programs written by a seasoned programmer not familiar with the language and corrections to these programs by a Go expert (from Google's development team), doing the same for Chapel, Cilk and Intel TBB. The study found that the non-expert tended to write divide-and-conquer algorithms with one statement per recursion, while the expert wrote distribute-work-synchronize programs using one goroutine per processor. The expert's programs were usually faster, but also longer.

paragraphs: There are no restrictions on how goroutines access shared data, making race conditions possible. Specifically, unless a program explicitly synchronizes via channels or other means, writes from one goroutine might be partly, entirely, or not at all visible to another, often with no guarantees about ordering of writes. Furthermore, Go's "internal data structures" like interface values, slice headers, hash tables, and string headers are not immune to race conditions, so type and memory safety can be violated in multithreaded programs that modify shared instances of those types without synchronization. Instead of language support, safe concurrent programming thus relies on conventions; for example, Chisnall recommends an idiom called "aliases xor mutable", meaning that passing a mutable value (or pointer) over a channel signals a transfer of ownership over the value to its receiver.

paragraphs: The linker in the gc toolchain creates statically linked binaries by default, therefore all Go binaries include the Go runtime.

paragraphs: Go deliberately omits certain features common in other languages, including (implementation) inheritance, generic programming, assertions, pointer arithmetic, implicit type conversions, untagged unions, and tagged unions. The designers added only those facilities that all three agreed on.

paragraphs: Of the omitted language features, the designers explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language, encouraging instead the use of interfaces to achieve dynamic dispatch and composition to reuse code. Composition and delegation are in fact largely automated by embedding; according to researchers Schmager "et al.", this feature "has many of the drawbacks of inheritance: it affects the public interface of objects, it is not fine-grained (i.e, no method-level control over embedding), methods of embedded objects cannot be hidden, and it is static", making it "not obvious" whether programmers will overuse it to the extent that programmers in other languages are reputed to overuse inheritance.

paragraphs: The designers express an openness to generic programming and note that built-in functions "are" in fact type-generic, but these are treated as special cases; Pike calls this a weakness that may at some point be changed. The Google team built at least one compiler for an experimental Go dialect with generics, but did not release it. They are also open to standardizing ways to apply code generation. In June 2020, a new draft design document was published, which would add the necessary syntax to Go for declaring generic functions and types. A code translation tool was provided to allow users to try out the new syntax, along with a generics-enabled version of the online Go Playground.

paragraphs: Initially omitted, the exception-like / mechanism was eventually added, which the Go authors advise using for unrecoverable errors such as those that should halt an entire program or server request, or as a shortcut to propagate errors up the stack within a package (but not across package boundaries; there, error returns are the standard API).

paragraphs: The Go authors put substantial effort into influencing the style of Go programs:

paragraphs: The main Go distribution includes tools for building, testing, and analyzing code:

paragraphs: It also includes profiling and debugging support, runtime instrumentation (for example, to track garbage collection pauses), and a race condition tester.

paragraphs: An ecosystem of third-party tools adds to the standard distribution, such as codice_50, which enables code autocompletion in many text editors, codice_51, which automatically adds/removes package imports as needed, and codice_52, which detects code that might unintentionally ignore errors.

paragraphs: where "fmt" is the package for "formatted I/O", similar to C's C file input/output.

paragraphs: The following simple program demonstrates Go's concurrency features to implement an asynchronous program. It launches two lightweight threads ("goroutines"): one waits for the user to type some text, while the other implements a timeout. The statement waits for either of these goroutines to send a message to the main routine, and acts on the first message to arrive (example adapted from David Chisnall book).

paragraphs: The testing package provides support for automated testing of go packages. Target function example:

paragraphs: func ExtractUsername(email string) string {

paragraphs: Test code (note that assert keyword is missing in Go; tests live in <filename>_test.go at the same package):

paragraphs: func TestExtractUsername(t *testing.T) {

paragraphs: It is possible to run tests in parallel.

paragraphs: Some notable open-source applications written in Go include:

paragraphs: Other notable companies and sites using Go (generally together with other languages, not exclusively) include:

paragraphs: The interface system, and the deliberate omission of inheritance, were praised by Michele Simionato, who likened these characteristics to those of Standard ML, calling it "a shame that no popular language has followed [this] particular route".

paragraphs: Go was named Programming Language of the Year by the TIOBE Programming Community Index in its first year, 2009, for having a larger 12-month increase in popularity (in only 2 months, after its introduction in November) than any other language that year, and reached 13th place by January 2010, surpassing established languages like Pascal. By June 2015, its ranking had dropped to below 50th in the index, placing it lower than COBOL and Fortran. But as of January 2017, its ranking had surged to 13th, indicating significant growth in popularity and adoption. Go was awarded TIOBE programming language of the year 2016.

paragraphs: A 2011 evaluation of the language and its implementation in comparison to C++ (GCC), Java and Scala by a Google engineer found:

paragraphs: The evaluation got a rebuttal from the Go development team. Ian Lance Taylor, who had improved the Go code for Hundt's paper, had not been aware of the intention to publish his code, and says that his version was "never intended to be an example of idiomatic or efficient Go"; Russ Cox then optimized the Go code, as well as the C++ code, and got the Go code to run slightly faster than C++ and more than an order of magnitude faster than the code in the paper.

paragraphs: On November 10, 2009, the day of the general release of the language, Francis McCabe, developer of the Go! programming language (note the exclamation point), requested a name change of Google's language to prevent confusion with his language, which he had spent 10 years developing. McCabe raised concerns that "the 'big guy' will end up steam-rollering over" him, and this concern resonated with the more than 120 developers who commented on Google's official issues thread saying they should change the name, with some even saying the issue contradicts Google's motto of: Don't be evil.

paragraphs: On October 12, 2010, the issue was closed by Google developer Russ Cox (@rsc) with the custom status "Unfortunate" accompanied by the following comment: "There are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages."


title: PostgreSQL

paragraphs: PostgreSQL (), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the Ingres database developed at the University of California, Berkeley. In 1996, the project was renamed to PostgreSQL to reflect its support for SQL. After a review in 2007, the development team decided to keep the name PostgreSQL and the alias Postgres.

paragraphs: PostgreSQL features transactions with Atomicity, Consistency, Isolation, Durability (ACID) properties, automatically updatable views, materialized views, triggers, foreign keys, and stored procedures. It is designed to handle a range of workloads, from single machines to data warehouses or Web services with many concurrent users. It is the default database for macOS Server, and is also available for Linux, FreeBSD, OpenBSD, and Windows.

paragraphs: PostgreSQL evolved from the Ingres project at the University of California, Berkeley. In 1982, the leader of the Ingres team, Michael Stonebraker, left Berkeley to make a proprietary version of Ingres. He returned to Berkeley in 1985, and began a post-Ingres project to address the problems with contemporary database systems that had become increasingly clear during the early 1980s. He won the Turing Award in 2014 for these and other projects, and techniques pioneered in them.

paragraphs: The new project, POSTGRES, aimed to add the fewest features needed to completely support data types. These features included the ability to define types and to fully describe relationships something used widely, but maintained entirely by the user. In POSTGRES, the database understood relationships, and could retrieve information in related tables in a natural way using "rules". POSTGRES used many of the ideas of Ingres, but not its code.

paragraphs: Starting in 1986, published papers described the basis of the system, and a prototype version was shown at the 1988 ACM SIGMOD Conference. The team released version 1 to a small number of users in June 1989, followed by version 2 with a re-written rules system in June 1990. Version 3, released in 1991, again re-wrote the rules system, and added support for multiple storage managers and an improved query engine. By 1993, the number of users began to overwhelm the project with requests for support and features. After releasing version 4.2 on June 30, 1994 primarily a cleanup the project ended. Berkeley released POSTGRES under an MIT License variant, which enabled other developers to use the code for any use. At the time, POSTGRES used an Ingres-influenced POSTQUEL query language interpreter, which could be interactively used with a console application named "monitor".

paragraphs: In 1994, Berkeley graduate students Andrew Yu and Jolly Chen replaced the POSTQUEL query language interpreter with one for the SQL query language, creating Postgres95. "monitor" was also replaced by psql. Yu and Chen announced the first version (0.01) to beta testers on May 5, 1995. Version 1.0 of Postgres95 was announced on September 5, 1995, with a more liberal license that enabled the software to be freely modifiable.

paragraphs: On July 8, 1996, Marc Fournier at Hub.org Networking Services provided the first non-university development server for the open-source development effort. With the participation of Bruce Momjian and Vadim B. Mikheev, work began to stabilize the code inherited from Berkeley.

paragraphs: In 1996, the project was renamed to PostgreSQL to reflect its support for SQL. The online presence at the website PostgreSQL.org began on October 22, 1996. The first PostgreSQL release formed version 6.0 on January 29, 1997. Since then developers and volunteers around the world have maintained the software as The PostgreSQL Global Development Group.

paragraphs: The project continues to make releases available under its free and open-source software PostgreSQL License. Code comes from contributions from proprietary vendors, support companies, and open-source programmers.

paragraphs: PostgreSQL manages concurrency through multiversion concurrency control (MVCC), which gives each transaction a "snapshot" of the database, allowing changes to be made without affecting other transactions. This largely eliminates the need for read locks, and ensures the database maintains ACID principles. PostgreSQL offers three levels of transaction isolation: Read Committed, Repeatable Read and Serializable. Because PostgreSQL is immune to dirty reads, requesting a Read Uncommitted transaction isolation level provides read committed instead. PostgreSQL supports full serializability via the serializable snapshot isolation (SSI) method.

paragraphs: PostgreSQL includes built-in binary replication based on shipping the changes (write-ahead logs (WAL)) to replica nodes asynchronously, with the ability to run read-only queries against these replicated nodes. This allows splitting read traffic among multiple nodes efficiently. Earlier replication software that allowed similar read scaling normally relied on adding replication triggers to the master, increasing load.

paragraphs: PostgreSQL includes built-in synchronous replication that ensures that, for each write transaction, the master waits until at least one replica node has written the data to its transaction log. Unlike other database systems, the durability of a transaction (whether it is asynchronous or synchronous) can be specified per-database, per-user, per-session or even per-transaction. This can be useful for workloads that do not require such guarantees, and may not be wanted for all data as it slows down performance due to the requirement of the confirmation of the transaction reaching the synchronous standby.

paragraphs: Standby servers can be synchronous or asynchronous. Synchronous standby servers can be specified in the configuration which determines which servers are candidates for synchronous replication. The first in the list that is actively streaming will be used as the current synchronous server. When this fails, the system fails over to the next in line.

paragraphs: Synchronous multi-master replication is not included in the PostgreSQL core. Postgres-XC which is based on PostgreSQL provides scalable synchronous multi-master replication. It is licensed under the same license as PostgreSQL. A related project is called Postgres-XL. Postgres-R is yet another fork. Bidirectional replication (BDR) is an asynchronous multi-master replication system for PostgreSQL.

paragraphs: Tools such as repmgr make managing replication clusters easier.

paragraphs: Several asynchronous trigger-based replication packages are available. These remain useful even after introduction of the expanded core abilities, for situations where binary replication of a full database cluster is inappropriate:

paragraphs: YugabyteDB is a database which uses the front-end of PostgreSQL with a more NoSQL-like backend. While it can be thought of as a different database, it is essentially PostgreSQL with a different storage backend. It addresses the replication issues with an implementation of the ideas from Google Spanner. Such databases are called NewSQL and include CockroachDB, and TiDB among others.

paragraphs: PostgreSQL includes built-in support for regular B-tree and hash table indexes, and four index access methods: generalized search trees (GiST), generalized inverted indexes (GIN), Space-Partitioned GiST (SP-GiST) and Block Range Indexes (BRIN). In addition, user-defined index methods can be created, although this is quite an involved process. Indexes in PostgreSQL also support the following features:

paragraphs: In PostgreSQL, a schema holds all objects, except for roles and tablespaces. Schemas effectively act like namespaces, allowing objects of the same name to co-exist in the same database. By default, newly created databases have a schema called "public", but any further schemas can be added, and the public schema isn't mandatory.

paragraphs: A setting determines the order in which PostgreSQL checks schemas for unqualified objects (those without a prefixed schema). By default, it is set to ( refers to the currently connected database user). This default can be set on a database or role level, but as it is a session parameter, it can be freely changed (even multiple times) during a client session, affecting that session only.

paragraphs: Non-existent schemas listed in search_path are silently skipped during objects lookup.

paragraphs: New objects are created in whichever valid schema (one that presently exists) appears first in the search_path.

paragraphs: A wide variety of native data types are supported, including:

paragraphs: In addition, users can create their own data types which can usually be made fully indexable via PostgreSQL's indexing infrastructures GiST, GIN, SP-GiST. Examples of these include the geographic information system (GIS) data types from the PostGIS project for PostgreSQL.

paragraphs: There is also a data type called a "domain", which is the same as any other data type but with optional constraints defined by the creator of that domain. This means any data entered into a column using the domain will have to conform to whichever constraints were defined as part of the domain.

paragraphs: A data type that represents a range of data can be used which are called range types. These can be discrete ranges (e.g. all integer values 1 to 10) or continuous ranges (e.g., any time between and ). The built-in range types available include ranges of integers, big integers, decimal numbers, time stamps (with and without time zone) and dates.

paragraphs: Custom range types can be created to make new types of ranges available, such as IP address ranges using the inet type as a base, or float ranges using the float data type as a base. Range types support inclusive and exclusive range boundaries using the / and / characters respectively. (e.g., represents all integers starting from and including 4 up to but not including 9.) Range types are also compatible with existing operators used to check for overlap, containment, right of etc.

paragraphs: New types of almost all objects inside the database can be created, including:

paragraphs: Tables can be set to inherit their characteristics from a "parent" table. Data in child tables will appear to exist in the parent tables, unless data is selected from the parent table using the ONLY keyword, i.e. . Adding a column in the parent table will cause that column to appear in the child table.

paragraphs: Inheritance can be used to implement table partitioning, using either triggers or rules to direct inserts to the parent table into the proper child tables.

paragraphs: , this feature is not fully supported yet in particular, table constraints are not currently inheritable. All check constraints and not-null constraints on a parent table are automatically inherited by its children. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited.

paragraphs: Inheritance provides a way to map the features of generalization hierarchies depicted in entity relationship diagrams (ERDs) directly into the PostgreSQL database.

paragraphs: PostgreSQL can link to other systems to retrieve data via foreign data wrappers (FDWs).

paragraphs: These can take the form of any data source, such as a file system, another relational database management system (RDBMS), or a web service. This means that regular database queries can use these data sources like regular tables, and even join multiple data-sources together.

paragraphs: For connecting to applications, PostgreSQL includes the built-in interfaces libpq (the official C application interface) and ECPG (an embedded C system). Third-party libraries for connecting to PostgreSQL are available for many programming languages, including C++, Java, Python, Node.js, Go, and Rust.

paragraphs: Procedural languages allow developers to extend the database with custom subroutines (functions), often called "stored procedures". These functions can be used to build database triggers (functions invoked on modification of certain data) and custom data types and aggregate functions. Procedural languages can also be invoked without defining a function, using a DO command at SQL level.

paragraphs: Languages are divided into two groups: Procedures written in "safe" languages are sandboxed and can be safely created and used by any user. Procedures written in "unsafe" languages can only be created by superusers, because they allow bypassing a database's security restrictions, but can also access sources external to the database. Some languages like Perl provide both safe and unsafe versions.

paragraphs: PostgreSQL has built-in support for three procedural languages:

paragraphs: In addition, PostgreSQL allows procedural languages to be loaded into the database through extensions. Three language extensions are included with PostgreSQL to support Perl, Python (by default Python 2, or Python 3 possible) and Tcl. There are external projects to add support for many other languages, including Java, JavaScript (PL/V8), R (PL/R), Ruby, and others.

paragraphs: Triggers are events triggered by the action of SQL data manipulation language (DML) statements. For example, an INSERT statement might activate a trigger that checks if the values of the statement are valid. Most triggers are only activated by either INSERT or UPDATE statements.

paragraphs: Triggers are fully supported and can be attached to tables. Triggers can be per-column and conditional, in that UPDATE triggers can target specific columns of a table, and triggers can be told to execute under a set of conditions as specified in the trigger's WHERE clause. Triggers can be attached to views by using the INSTEAD OF condition. Multiple triggers are fired in alphabetical order. In addition to calling functions written in the native PL/pgSQL, triggers can also invoke functions written in other languages like PL/Python or PL/Perl.

paragraphs: PostgreSQL provides an asynchronous messaging system that is accessed through the NOTIFY, LISTEN and UNLISTEN commands. A session can issue a NOTIFY command, along with the user-specified channel and an optional payload, to mark a particular event occurring. Other sessions are able to detect these events by issuing a LISTEN command, which can listen to a particular channel. This functionality can be used for a wide variety of purposes, such as letting other sessions know when a table has updated or for separate applications to detect when a particular action has been performed. Such a system prevents the need for continuous polling by applications to see if anything has yet changed, and reducing unnecessary overhead. Notifications are fully transactional, in that messages are not sent until the transaction they were sent from is committed. This eliminates the problem of messages being sent for an action being performed which is then rolled back.

paragraphs: Many connectors for PostgreSQL provide support for this notification system (including libpq, JDBC, Npgsql, psycopg and node.js) so it can be used by external applications.

paragraphs: PostgreSQL can act as an effective, persistent "pub/sub" server or job server by combining LISTEN with FOR UPDATE SKIP LOCKED, a combination which has existed since PostgreSQL version 9.5

paragraphs: Rules allow the "query tree" of an incoming query to be rewritten. "Query Re-Write Rules" are attached to a table/class and "Re-Write" the incoming DML (select, insert, update, and/or delete) into one or more queries that either replace the original DML statement or execute in addition to it. Query Re-Write occurs after DML statement parsing, but before query planning.

paragraphs: PostgreSQL server is process-based (not threaded), and uses one operating system process per database session. Multiple sessions are automatically spread across all available CPUs by the operating system. Starting with PostgreSQL 9.6, many types of queries can also be parallelized across multiple background worker processes, taking advantage of multiple CPUs or cores. Client applications can use threads and create multiple database connections from each thread.

paragraphs: PostgreSQL manages its internal security on a per-role basis. A role is generally regarded to be a user (a role that can log in), or a group (a role of which other roles are members). Permissions can be granted or revoked on any object down to the column level, and can also allow/prevent the creation of new objects at the database, schema or table levels.

paragraphs: PostgreSQL's SECURITY LABEL feature (extension to SQL standards), allows for additional security; with a bundled loadable module that supports label-based mandatory access control (MAC) based on Security-Enhanced Linux (SELinux) security policy.

paragraphs: PostgreSQL natively supports a broad number of external authentication mechanisms, including:

paragraphs: The GSSAPI, SSPI, Kerberos, peer, ident and certificate methods can also use a specified "map" file that lists which users matched by that authentication system are allowed to connect as a specific database user.

paragraphs: These methods are specified in the cluster's host-based authentication configuration file (pg_hba.conf), which determines what connections are allowed. This allows control over which user can connect to which database, where they can connect from (IP address, IP address range, domain socket), which authentication system will be enforced, and whether the connection must use Transport Layer Security (TLS).

paragraphs: PostgreSQL claims high, but not complete, conformance with the SQL standard. One exception is the handling of unquoted identifiers like table or column names. In PostgreSQL they are folded, internally, to lower case characters whereas the standard says that unquoted identifiers should be folded to upper case. Thus, should be equivalent to not according to the standard.

paragraphs: Many informal performance studies of PostgreSQL have been done. Performance improvements aimed at improving scalability began heavily with version 8.1. Simple benchmarks between version 8.0 and version 8.4 showed that the latter was more than 10 times faster on read-only workloads and at least 7.5 times faster on both read and write workloads.

paragraphs: The first industry-standard and peer-validated benchmark was completed in June 2007, using the Sun Java System Application Server (proprietary version of GlassFish) 9.0 Platform Edition, UltraSPARC T1-based Sun Fire server and PostgreSQL 8.2. This result of 778.14 SPECjAppServer2004 JOPS@Standard compares favourably with the 874 JOPS@Standard with Oracle 10 on an Itanium-based HP-UX system.

paragraphs: In August 2007, Sun submitted an improved benchmark score of 813.73 SPECjAppServer2004 JOPS@Standard. With the system under test at a reduced price, the price/performance improved from $84.98/JOPS to $70.57/JOPS.

paragraphs: The default configuration of PostgreSQL uses only a small amount of dedicated memory for performance-critical purposes such as caching database blocks and sorting. This limitation is primarily because older operating systems required kernel changes to allow allocating large blocks of shared memory. PostgreSQL.org provides advice on basic recommended performance practice in a wiki.

paragraphs: In April 2012, Robert Haas of EnterpriseDB demonstrated PostgreSQL 9.2's linear CPU scalability using a server with 64 cores.

paragraphs: Matloob Khushi performed benchmarking between Postgresql 9.0 and MySQL 5.6.15 for their ability to process genomic data. In his performance analysis he found that PostgreSQL extracts overlapping genomic regions eight times faster than MySQL using two datasets of 80,000 each forming random human DNA regions. Insertion and data uploads in PostgreSQL were also better, although general searching ability of both databases was almost equivalent.

paragraphs: PostgreSQL is available for the following operating systems: Linux (all recent distributions), 64-bit installers available for macOS (OS X) version 10.6 and newer Windows (with installers available for 64-bit version; tested on latest versions and back to Windows 2012 R2, while for PostgreSQL version 10 and older a 32-bit installer is available and tested down to 32-bit Windows 2008 R1; compilable by e.g. Visual Studio, version 2013 up to the most recent 2019 version) FreeBSD, OpenBSD, NetBSD, AIX, HP-UX, Solaris, and UnixWare; and not officially tested: DragonFly BSD, BSD/OS, IRIX, OpenIndiana, OpenSolaris, OpenServer, and Tru64 UNIX. Most other Unix-like systems could also work; most modern do support.

paragraphs: PostgreSQL works on any of the following instruction set architectures: x86 and x86-64 on Windows and other operating systems; these are supported on other than Windows: IA-64 Itanium (external support for HP-UX), PowerPC, PowerPC 64, S/390, S/390x, SPARC, SPARC 64, ARMv8-A (64-bit) and older ARM (32-bit, including older such as ARMv6 in Raspberry Pi), MIPS, MIPSel, and PA-RISC. It was also known to work on some other platforms (while not been tested on for years, i.e. for latest versions).

paragraphs: Open source front-ends and tools for administering PostgreSQL include:

paragraphs: A number of companies offer proprietary tools for PostgreSQL. They often consist of a universal core that is adapted for various specific database products. These tools mostly share the administration features with the open source tools but offer improvements in data modeling, importing, exporting or reporting.

paragraphs: Notable organizations and products that use PostgreSQL as the primary database include:

paragraphs: Some notable vendors offer PostgreSQL as software as a service:


title: Swift (programming language)

paragraphs: Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community, first released in 2014. Swift was developed as a replacement for Apple's earlier programming language Objective-C, as Objective-C had been largely unchanged since the early 1980s and lacked modern language features. Swift works with Apple's Cocoa and Cocoa Touch frameworks, and a key aspect of Swift's design was the ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades. It is built with the open source LLVM compiler framework and has been included in Xcode since version 6, released in 2014. On Apple platforms, it uses the Objective-C runtime library which allows C, Objective-C, C++ and Swift code to run within one program.

paragraphs: 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).

paragraphs: Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a more major upgrade to Swift 2 at WWDC 2015. Initially a proprietary language, version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple's platforms and Linux.

paragraphs: Through version 3.0 the syntax of Swift went through significant evolution, with the core team making source stability a focus in later versions. In the first quarter of 2018 Swift surpassed Objective-C in measured popularity.

paragraphs: 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.

paragraphs: 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.

paragraphs: Development of Swift started in July 2010 by Chris Lattner, with the eventual collaboration of many other programmers at Apple. Swift took language ideas "from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list". On June 2, 2014, the Apple Worldwide Developers Conference (WWDC) application became the first publicly released app written with Swift. 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.

paragraphs: "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.

paragraphs: Swift reached the 1.0 milestone on September 9, 2014, with the "Gold Master" of Xcode 6.0 for iOS. Swift 1.1 was released on October 22, 2014, alongside the launch of Xcode 6.1. Swift 1.2 was released on April 8, 2015, along with Xcode 6.3. Swift 2.0 was announced at WWDC 2015, and was made available for publishing apps in the App Store in September 21, 2015. Swift 3.0 was released on September 13, 2016. Swift 4.0 was released on September 19, 2017. Swift 4.1 was released on March 29, 2018.

paragraphs: Swift won first place for "Most Loved Programming Language" in the Stack Overflow Developer Survey 2015 and second place in 2016.

paragraphs: 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, 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.

paragraphs: In December 2015, IBM announced its Swift Sandbox website, which allows developers to write Swift code in one pane and display output in another. The Swift Sandbox was deprecated in January 2018.

paragraphs: 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.

paragraphs: 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.

paragraphs: During WWDC 2019, Apple announced SwiftUI, which provides a framework for declarative UI structure design across all Apple platforms.

paragraphs: Official downloads 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. There is an unofficial package for Android too.

paragraphs: Languages do not strictly support operating systems, the associated libraries (and compilers) do. Swift is not officially supported by Android yet, but unofficial toolchains are available, such as the Swift Android Toolchain, keeping some compatibility with Apple's allowing cross-platform programs.

paragraphs: The platforms Swift supports are Apple's operating systems (Darwin, iOS, iPadOS, macOS, tvOS, watchOS), Linux, Windows, and Android. An unofficial port for FreeBSD also exists.

paragraphs: 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".

paragraphs: 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 a Smalltalk-like syntax for making method calls has been replaced with a dot-notation style and namespace system more familiar to programmers from other common object-oriented (OO) languages like Java or C#. Swift introduces true named parameters and retains key Objective-C concepts, including protocols, closures and categories, often replacing former syntax with cleaner versions and allowing these concepts to be applied to other language structures, like enumerated types (enums)

paragraphs: Swift supports closures (known as lambdas in other languages). Here is an example:

paragraphs: Swift has a trailing closure syntax like this:

paragraphs: // This function takes a closure or function that returns an int and then just evaluates the function.

paragraphs: Starting from version 5.3, Swift supports multiple trailing closures:

paragraphs: // This function passes the result of the first closure or function to another and returns its result.

paragraphs: func b(closure a: () -> Int, anotherClosure: (Int) -> Int) -> Int {

paragraphs: a(closure: {return 1}, anotherClosure: {x in return x + 1})

paragraphs: a(closure: {return 1}) {x in return x + 1})

paragraphs: Here is the criteria for the trailing closure syntax:

paragraphs: Under the Cocoa and Cocoa Touch environments, many common classes were part of the Foundation Kit library. This included the NSString string library (using Unicode, UTF-8 in Swift 5, changed from UTF-16), the NSArray and NSDictionary collection classes, and others. Objective-C provided various bits of syntactic sugar to allow some of these objects to be created on-the-fly within the language, but once created, the objects were manipulated with object calls. For instance, in Objective-C concatenating two NSStrings required method calls similar to this:

paragraphs: str = [str stringByAppendingString:@" world"]; In Swift, many of these basic types have been promoted to the language's core, and can be manipulated directly. For instance, strings are invisibly bridged to NSString (when Foundation is imported) and can now be concatenated with the codice_2 operator, allowing greatly simplified syntax; the prior example becoming:

paragraphs: Swift supports five access control levels for symbols: , , , , and . Unlike many object-oriented languages, these access controls ignore inheritance hierarchies: indicates that a symbol is accessible only in the immediate scope, indicates it is accessible only from within the file, indicates it is accessible within the containing module, indicates it is accessible from any module, and (only for classes and their methods) indicates that the class may be subclassed outside of the module.

paragraphs: An important new 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 refer to a value or may be null. This implies that non-optional types cannot result in a null-pointer error; the compiler can ensure this is not possible.

paragraphs: Optional types are created with the codice_3 mechanism—to make an Integer that is nullable, one would use a declaration similar to codice_4. 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, codice_5. Variables or constants that are marked optional either have a value of the underlying type or are codice_6. Optional types "wrap" the base type, resulting in a different instance. codice_7 and codice_8 are fundamentally different types, the latter has more in common with codice_9 than codice_7.

paragraphs: To access the value inside, assuming it is not nil, it must be "unwrapped" to expose the instance inside. This is performed with the codice_11 operator:

paragraphs: let myValue = anOptionalInstance!.someMethod()

paragraphs: In this case, the codice_11 operator unwraps codice_13 to expose the instance inside, allowing the method call to be made on it. If codice_13 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:

paragraphs: let myValue = anOptionalInstance?.someMethod()

paragraphs: In this case the runtime calls codice_15 only if codice_13 is not nil, suppressing the error. Normally this requires the programmer to test whether codice_17 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:

paragraphs: let leaseStart = aBuilding.tenantList[5].leaseDetails?.startDate

paragraphs: The codice_18 syntax circumvents the pyramid of doom.

paragraphs: Swift 2 introduced the new keyword codice_1 for cases in which code should stop executing if some condition is unmet:

paragraphs: guard let leaseStart = aBuilding.TenantList[5]?.leaseDetails?.startDate else

paragraphs: //continue, knowing that leaseStart is not nil

paragraphs: Using codice_1 has three benefits. While the syntax can act as an codice_21 statement, its primary benefit is inferring non-nullability. Where an codice_21 statement requires a case, codice_1 assumes the case based on the condition provided. Also, since codice_1 contains no scope, with exception of the codice_25 closure, codice_26 is presented as an unwrapped optional to the guard's super-scope. Lastly, if the codice_1 statement's test fails, Swift requires the codice_25 to exit the current method or loop, ensuring codice_26 never is accessed when codice_6. This is performed with the keywords codice_31, codice_32, codice_33, or codice_34, or by calling a function returning a codice_35 (e.g. codice_36).

paragraphs: 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:

paragraphs: leaseStart = [[[aBuilding tenantList:5] leaseDetails] startDate]

paragraphs: Would return nil, and this could be tested. However, this also demanded that all method calls be dynamic, which introduces significant overhead. Swift's use of optionals provides a similar mechanism for testing and dealing with nils, but does so in a way that allows the compiler to use [[static dispatch]] because the unwrapping action is called on a defined instance (the wrapper), versus occurring in the runtime dispatch system.

paragraphs: In many object-oriented languages, objects are represented internally in two parts. The object is stored as a block of data placed on the [[Heap (data structure)|heap]], while the name (or "handle") to that object is represented by a [[Pointer (computer programming)|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.

paragraphs: 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 (computer architecture)|word]]), so there is no advantage to passing a pointer, versus passing the value. Also, pass-by-reference inherently requires a dereferencing operation, which can produce noticeable overhead in some operations, typically those used with these basic value types, like mathematics.

paragraphs: Similarly to C# and in contrast to most other OO languages, Swift offers built-in support for objects using either pass-by-reference or pass-by-value semantics, the former using the codice_37 declaration and the latter using codice_38. 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.

paragraphs: 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 codice_39 and codice_40, and types normally represented by objects, like codice_7 and codice_42. Using value types can result in significant performance improvements in user applications as well.

paragraphs: 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.

paragraphs: 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 add [[spell checker]] support to the base codice_43 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 codice_44. Unlike Objective-C, Swift can also add new properties accessors, types, and enums to extant instances .

paragraphs: Another key feature of Objective-C is its use of [[Protocol (object-oriented programming)|"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 codice_45 protocol, which defines one method, codice_46, that implements [[object copying#deep copy|deep copying]] on objects.

paragraphs: 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.

paragraphs: For example, a protocol might be declared called codice_47, which ensures that instances that conform to the protocol implement a codice_48 method that returns a codice_7. In Swift, this can be declared with code like this:

paragraphs: This protocol can now be added to String, with no access to the base class's source:

paragraphs: 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:

paragraphs: It does not matter what sort of instance codice_50 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 codice_51.

paragraphs: 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 codice_52 protocol to many of their basic types, like Strings and Arrays, allowing them to be compared with the codice_53 operator. A concrete example of how all of these features interact can be seen in the concept of "default protocol implementations":

paragraphs: func !=<T : Equatable>(lhs: T, rhs: T) -> Bool

paragraphs: This function defines a method that works on any instance conforming to codice_52, providing a "not equals" function. Any instance, class or struct, automatically gains this implementation simply by conforming to codice_52. As many instances gain codice_52 through their base implementations or other generic extensions, most basic objects in the runtime gain equals and not equals with no code.

paragraphs: 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.

paragraphs: 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.

paragraphs: 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 codice_57. 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.

paragraphs: 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 codice_58 syntax, but the currently available set is small. One example is the codice_59 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.

paragraphs: 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]].

paragraphs: Swift uses [[Automatic Reference Counting]] (ARC) to [[Memory management|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 "[[Reference counting#reference cycle|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 codice_60 and codice_61 to prevent strong reference cycles. Typically a parent-child relationship would use a strong reference while a child-parent would use either codice_60 reference, where parents and children can be unrelated, or codice_61 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 codice_6.

paragraphs: 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."

paragraphs: 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]] languages. The REPL is further enhanced with the new concept "[[Swift Playgrounds|playgrounds]]". These are interactive views running within the Xcode environment that respond to code or debugger changes on-the-fly. [[Swift Playgrounds|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.

paragraphs: Apple says that Swift is "an industrial-quality programming language that's as expressive and enjoyable as a scripting language".

paragraphs: Many of the features introduced with Swift have well-known performance and safety trade-offs. Apple has implemented [[Optimizing compiler|optimizations]] that reduce this overhead.

paragraphs: It also has similarities to Objective-C:

paragraphs: 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 (server framework)|Perfect]] and [[Vapor (Server-side Swift)|Vapor]].

paragraphs: An official "Server APIs" work group has also been started by Apple, with members of the Swift developer community playing a central role.

paragraphs: A second free implementation of Swift that targets [[Cocoa (API)|Cocoa]], [[Microsoft]]'s [[Common Language Infrastructure]] ([[.NET Framework|.NET]]), and the [[Java (software platform)|Java]] and [[Android (operating system)|Android]] platform exists as part of the "Elements Compiler" from [[RemObjects Software]].

paragraphs: By combining [[toolchain]]s from LLVM and [[Macintosh Programmer's Workshop]], it is possible to run a very small subset of the language on [[Mac OS 9]].

paragraphs: [[Category:Computer-related introductions in 2014]]

paragraphs: [[Category:Pattern matching programming languages]]

paragraphs: [[Category:Programming languages created in 2014]]

paragraphs: [[Category:Software using the Apache license]]

paragraphs: [[Category:Statically typed programming languages]]