Filling an Array

Just as there are multiple ways to create a variable in Swift, there are also multiple ways to create an array in Swift. The most straightforward way, similar to older programming languages, is to define an array to hold a specific data type and create an empty array.

One way to create an empty array is to use the equal sign and empty parentheses like this:

var firstArray = [Int]()

A second way to create an empty array is to use a colon, an equal sign, and empty square brackets like this:

var secondArray : [Int] = []

These two methods force you to specifically define the data type the array holds such as all integers (Int) or all decimal numbers (Double or Float). A third method lets Swift infer the data type by just specifying at least one item in the array. Based on that one item, Swift can infer the data type that array can hold. So if you wanted to create an array that can only hold integers, you could use inference to create an array like this:

var thirdArray = [0]

A fourth way to create an array gives you the option of creating an array filled with a multiple copies of the same value. So if you needed to create an initial array filled with twenty number 5s, you could explicitly type all twenty 5s, or you could use the repeating, count feature of creating arrays, which looks like this:

var fourthArray : [Int] = Array (repeating: 3, count: 2)

var fifthArray = Array (repeating: 3, count: 2)

You could explicitly define the data type or leave it out and let Swift infer the data type based on the data you use. The Swift code above creates an array of integers that holds 2 copies of the number 3.

Use whatever method you like best for creating arrays. If you’re familiar with older programming languages, you’re probably already in the habit of explicitly declaring the data type of an array so you can choose which method you like best.

If you want to let Swift infer the data type, then you’ll need to explicitly define at least one value when creating that array.

If you need to create an array to hold identical copies of the same data, then you can use the unique repeating, count feature to specify the data to use and how many copies to insert in the array.

No single method is the “best” so just use whatever method you prefer. In general, rely on Swift inference because it makes your code shorter although you may still prefer explicitly declaring data types so it’s crystal clear exactly what data that array can hold.

October 6th, 2016 by
HTML Snippets Powered By :