Swift Array Initialization
Array initialization in Swift means creating an Array value and defining the type of elements it can store. You can initialize an empty array, create an array with repeated default values, provide initial values directly, build an array from a range or another sequence, or create an array of custom objects.
Swift arrays are ordered collections. Every element in a single array must have the same type, such as Int, String, or a custom structure. When the initial values make the element type clear, Swift can usually infer the type.
Common Ways to Initialize an Array in Swift
- Create an empty array with an explicit element type.
- Create an array with a specific size and repeated default value.
- Create an array from a list of initial values.
- Create an array from a range or another sequence.
- Initialize an array of optional values, nested arrays, or custom objects.
Create an Empty Array
To create an empty Array, use the following syntax.
var array_name = [datatype]()
Examples
Following are the examples to create an empty Integer Array and an empty String Array.
// integer array
var numbers = [Int]()
// string array
var name = [String]()
You can also write the element type before the assignment. Both forms create an empty array of the specified type.
var scores: [Int] = []
var cities: Array<String> = []
Use var when elements will be appended, removed, or replaced. Use let when the array must remain unchanged after initialization.
var editableNames: [String] = []
let fixedNames: [String] = []
Create an Array with Specific Size
To create an Integer Array with specific size and default values, use the following syntax.
var array_name = [Int](count: array_size, repeatedValue: default_value)
The preceding initializer uses older Swift syntax. In current Swift, initialize an array of a specific size with Array(repeating:count:), as shown in the next syntax.
var arrayName = [ElementType](repeating: defaultValue, count: arraySize)
To create a String Array with specific size and default values, use the following syntax.
var array_name = [String](repeating: default_value, count: array_size)
Examples
Following are the examples to create Arrays with a specific size and a default value for each item in the Array.
// integer array
var numbers = [Int](count: 3, repeatedValue: 20)
// string array
var name = [String](repeating:"tutorialkart", count:5)
For current Swift code, use the repeating:count: initializer for every element type.
let zeros = [Int](repeating: 0, count: 5)
let placeholders = [String](repeating: "Pending", count: 3)
print(zeros)
print(placeholders)
[0, 0, 0, 0, 0]
["Pending", "Pending", "Pending"]
The count argument must not be negative. A count of 0 creates an empty array.
Create an Array with some Initial Values
To create an Array with some , use the following syntax.
var array_name:[datatype] = [value1, value2, .., valueN]
Examples
Following are the examples to create an empty Integer Array and an empty String Array.
// integer array
var numbers:[Int] = [25, 78, 56]
// string array
var name:[String] = ["TutorialKart", "Swift Tutorial", "iOS Tutorial"]
Because all values in each array have the same clear type, the explicit type annotation can be omitted.
let numbers = [25, 78, 56]
let names = ["TutorialKart", "Swift Tutorial", "iOS Tutorial"]
Swift infers [Int] for numbers and [String] for names. Add an explicit type when the intended element type is not obvious or when values can be converted to more than one compatible type.
Initialize a Swift Array from a Range
Use the Array initializer to convert a range into an array. A closed range includes both endpoints, while a half-open range excludes its upper endpoint.
let oneToFive = Array(1...5)
let zeroToFour = Array(0..<5)
print(oneToFive)
print(zeroToFour)
[1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
Initialize a Swift Array from Another Sequence
Array(sequence) creates an array containing the elements produced by another sequence. This is useful when converting sets, strings, ranges, or filtered sequence results into arrays.
let word = "Swift"
let characters = Array(word)
print(characters)
["S", "w", "i", "f", "t"]
Initialize a Swift Array with Generated Values
When each element should be calculated from its position, create the array from a range and transform the values with map.
let squares = (1...5).map { number in
number * number
}
print(squares)
[1, 4, 9, 16, 25]
Initialize an Array of Optional Values in Swift
An array can store optional values when each position may contain either a value or nil. Specify the optional element type explicitly.
var results = [Int?](repeating: nil, count: 4)
results[0] = 85
results[2] = 92
print(results)
[Optional(85), nil, Optional(92), nil]
Initialize a Two-Dimensional Array in Swift
A two-dimensional array is an array whose elements are also arrays. The following example creates three rows, with four integer values in each row.
let columns = 4
let rows = 3
let grid = [[Int]](
repeating: [Int](repeating: 0, count: columns),
count: rows
)
print(grid)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Swift arrays have value semantics. When an inner array value is changed through one row, Swift preserves the expected independent value behavior rather than treating every row as the same mutable object reference.
Initialize an Array of Custom Objects or Structures
You can initialize an array with instances of a custom type. In the following example, Swift infers the array type as [Product].
struct Product {
let name: String
let price: Double
}
let products = [
Product(name: "Notebook", price: 3.50),
Product(name: "Pen", price: 1.25)
]
print(products.count)
2
Choose var or let When Initializing Swift Arrays
Declare an array with var when its contents will change. Declare it with let when neither its elements nor its size should be modified after initialization.
var tasks = ["Design", "Build"]
tasks.append("Test")
let weekdays = ["Monday", "Tuesday", "Wednesday"]
Common Swift Array Initialization Mistakes
- Writing
var values = []without an element type. Swift cannot infer the type of an empty array from an empty literal alone. - Using the obsolete
count:repeatedValue:initializer in current Swift code instead ofrepeating:count:. - Mixing incompatible element types in the same array without defining a suitable common type.
- Using a negative value for the
countargument. - Declaring an array with
letand then attempting to append, remove, or replace elements. - Confusing an empty array such as
[Int]()with an array that contains optionalnilvalues.
Swift Array Initialization FAQs
What is array initialization in Swift?
Array initialization creates an array value and establishes the type and initial contents of its elements. The array may begin empty, contain supplied values, or contain a repeated default value.
How do I initialize an empty array in Swift?
Specify the element type and use empty brackets or the type initializer, such as var values: [Int] = [] or var values = [Int]().
How do I initialize a Swift array with a fixed size?
Use [Type](repeating: value, count: size). Swift arrays are dynamically sized, so this creates the requested initial number of elements but does not prevent later resizing when the array is declared with var.
How do I initialize a String array in Swift?
Use an explicit type for an empty array, such as var names: [String] = [], or provide string values directly, such as let names = ["Asha", "Ravi"].
How do I create a Swift array from a range?
Pass the range to the Array initializer. For example, Array(1...5) creates [1, 2, 3, 4, 5].
Editorial QA Checklist for Swift Array Initialization
- Confirm that current examples use
repeating:count:for repeated-value initialization. - Verify that every empty array has an explicit element type.
- Check that examples distinguish a requested initial count from a permanently fixed-size collection.
- Ensure range examples correctly explain closed and half-open ranges.
- Verify that nested-array dimensions and output contain the stated number of rows and columns.
- Check that code using
letdoes not later mutate the array.
Summary of Array Initialization in Swift
Use [Type]() or var values: [Type] = [] for an empty array, [Type](repeating:count:) for repeated default values, and an array literal for known initial values. The Array initializer can also convert ranges and other sequences into arrays. Choose var for mutable arrays and let for arrays that should remain unchanged.
In this Swift Tutorial, we have learned how to initialize an Array with the help of example Swift Programs.
TutorialKart.com