Declare An Array In Swift
Code snippet for how to Declare An Array In Swift with sample and detail explanation
The Swift language is loaded with rich features, one of which includes arrays. This article will provide a simplified tutorial on how to declare an array in Swift language.
Code Snippet to Declare an Array
In Swift, you can create an array in two ways. Here are examples of different arrays declaration:
// Method 1: Array Declaration with data type but no size and elements
var array1: [Int]
// Method 2: Array Declaration with data type, size, and default elements
var array2 = [Int](repeating: 0, count: 5)
// Method 3: Array Declaration with specific elements
var array3 = [1, 2, 3, 4, 5]
Code Explanation for Array Declaration
Let’s break these array declaration methods down for a better understanding.
In Method 1
, var array1: [Int]
, an array named array1
is declared where we have only specified the data type that the array will hold, in this case, Int (integer). However, this array does not have any size and elements at the time of declaration. Please note that this array will produce a compile-time error if used before adding elements.
In Method 2
, var array2 = [Int](repeating: 0, count: 5)
, an array named array2
is declared. This time, we have not only specified the array’s type (Int) but also its size (5) and default elements (0). Here, all five elements in the array will implicitly be set to zero.
Lastly, Method 3
, var array3 = [1, 2, 3, 4, 5]
is the most straight-forward way to declare an array. Here array3
is an array of integers that has five elements: 1, 2, 3, 4, and 5.
In all the examples above, ‘var’ is used to declare an array, indicating that the array is mutable, meaning we can modify its elements and its length. If you want to create an immutable array, replace ‘var’ with ‘let’.
This concludes the simple tutorial on how to declare arrays in Swift. Hopefully, this clarifies the different ways you can declare an array in your next Swift development project. There’s a lot more to explore with arrays such as array operations, which may be covered in another tutorial.