Swift Array Initialization
Welcome to Swift Tutorial. In this tutorial, we will learn how to initialize Arrays in Swift.
Arrays initialization can be done in three ways.
- Create an empty array
- Create an array with Specific Size and Default Values
- Create an array with some Initial Values
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]()
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)
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)
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"]
Conclusion
In this Swift Tutorial, we have learned how to initialize an Array with the help of example Swift Programs.