A type that can be initialized using an array literal.
- Xcode 8.0+
- Swift Standard Library
An array literal is a simple way of expressing a list of values. Simply surround a comma-separated list of values, instances, or literals with square brackets to create an array literal. You can use an array literal anywhere an instance of an
Expressible type is expected: as a value assigned to a variable or constant, as a parameter to a method or initializer, or even as the subject of a nonmutating operation like
Arrays, sets, and option sets all conform to
Expressible, and your own custom types can as well. Here’s an example of creating a set and an array using array literals:
Array types each handle array literals in their own way to create new instances. In this case, the newly created set drops the duplicate value (“Dave”) and doesn’t maintain the order of the array literal’s elements. The new array, on the other hand, matches the order and number of elements provided.
Type Inference of Array Literals
Whenever possible, Swift’s compiler infers the full intended type of your array literal. Because
Array is the default type for an array literal, without writing any other code, you can declare an array with a particular element type by providing one or more values.
In this example, the compiler infers the full type of each array literal.
An empty array literal alone doesn’t provide enough information for the compiler to infer the intended type of the
Array instance. When using an empty array literal, specify the type of the variable or constant.
Because many functions and initializers fully specify the types of their parameters, you can often use an array literal with or without elements as a parameter. For example, the
sum(_:) function shown here takes an
Int array as a parameter:
When you call a function that does not fully specify its parameters’ types, use the type-cast operator (
as) to specify the type of an array literal. For example, the
log(name: function shown here has an unconstrained generic
Conforming to ExpressibleByArrayLiteral
Add the capability to be initialized with an array literal to your own custom types by declaring an
init(array initializer. The following example shows the array literal initializer for a hypothetical
Ordered type, which has setlike semantics but maintains the order of its elements.