protocol
ExpressibleByArrayLiteral
Inheritance | View Protocol Hierarchy → |
---|---|
Associated Types |
The type of the elements of an array literal. |
Import |
|
Initializers
Creates an instance initialized with the given elements.
Declaration
init
(
arrayLiteral
elements
:
Self
.
Element
...)
A type that can be initialized using an array literal.
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
ExpressibleByArrayLiteral
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 likemap(_:)
orfilter(_:)
.Arrays, sets, and option sets all conform to
ExpressibleByArrayLiteral
, and your own custom types can as well. Here's an example of creating a set and an array using array literals:The
Set
andArray
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.Note: An array literal is not the same as an
Array
instance. You can't initialize a type that conforms toExpressibleByArrayLiteral
simply by assigning an existing array.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 anInt
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, thelog(name:value:)
function shown here has an unconstrained genericvalue
parameter.Conforming to ExpressibleByArrayLiteral
Add the capability to be initialized with an array literal to your own custom types by declaring an
init(arrayLiteral:)
initializer. The following example shows the array literal initializer for a hypotheticalOrderedSet
type, which has setlike semantics but maintains the order of its elements.