C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example 1: Here we specify the 4 strings in square brackets. We do not specify "String" anywhere.
Example 2: We create an empty Array and then append elements to it. This version requires more lines of code.
Example 3: Uses an "arrayLiteral" argument to the Array initialization method. This requires just one line.
Example 4: Initializes an empty String array. It specifies the type and then uses append.
Swift program that initializes arrays
// Initialize array with 4 strings.
let words = ["the", "cat", "is", "cute"]
print(words)
// 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)
// Initialize with an arrayLiteral argument.
let words3 = Array<String>(arrayLiteral: "the", "cat", "is", "cute")
print(words3)
// Initialize as empty array.
var words4: [String] = []
words4.append("the")
words4.append("cat")
words4.append("is")
words4.append("cute")
print(words4)
Output
["the", "cat", "is", "cute"]
["the", "cat", "is", "cute"]
["the", "cat", "is", "cute"]
["the", "cat", "is", "cute"]
Swift program that splits string
import Foundation
// An array can be initialized from a string.
// ... This approach is slower.
let words5 = "the cat is cute".components(separatedBy: " ")
print(words5)
Output
["the", "cat", "is", "cute"]
Initialization error: Swift
var codes: [Int]
// We need to assign "codes" to an empty array before using append.
codes.append(1)
Output
/Users/.../Desktop/Test/Test/main.swift:2:7:
Variable 'codes' passed by reference before being initialized
Swift program that initializes empty Int array
var codes: [Int] = []
// This code sample works.
codes.append(1)