In Swift we often create arrays. But many forms of syntax can be used. Some forms are more verbose, and others easier to read.
With the Array class
, we can specify the element type directly. But this is not always needed. A lightweight syntax is available for arrays.
Let us begin with this example. In it we create 4 different arrays. The arrays all have the same elements (saying "the cat is cute").
String
" anywhere.arrayLiteral
" argument to the Array initialization method. This requires just one line.String
array. We specify the type and then use append.// Version 1: initialize array with 4 strings. let words = ["the", "cat", "is", "cute"] print(words) // Version 2: initialize with Array class and element type. var words2 = Array<String>() words2.append("the") words2.append("cat") words2.append("is") words2.append("cute") print(words2) // Version 3: initialize with an arrayLiteral argument. let words3 = Array<String>(arrayLiteral: "the", "cat", "is", "cute") print(words3) // Version 4: initialize as empty array. var words4: [String] = [] words4.append("the") words4.append("cat") words4.append("is") words4.append("cute") print(words4)["the", "cat", "is", "cute"] ["the", "cat", "is", "cute"] ["the", "cat", "is", "cute"] ["the", "cat", "is", "cute"]
This version of Swift code is less efficient. But we can initialize string
arrays from string
literals. Sometimes this is required.
import Foundation // An array can be initialized from a string. // ... This approach is slower. let words5 = "the cat is cute".components(separatedBy: " ") print(words5)["the", "cat", "is", "cute"]
Sometimes things do not go our way in life. Here we forget to specify an initialization. We specify the array type, but this is not enough.
var codes: [Int] // We need to assign "codes" to an empty array before using append. codes.append(1)/Users/.../Desktop/Test/Test/main.swift:2:7: Variable 'codes' passed by reference before being initialized
Here we fix the array initialization error from the previous example. We just use an empty array, and the code works.
var codes: [Int] = [] // This code sample works. codes.append(1)
In Swift, array initialization can be done in many ways. Typically, I prefer the shortest syntax form possible. But this does not work when array initializations are complex.