C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Var: We use the var keyword to declare the array. This is a variable array, which means it can be changed.
Print: This method prints the array count and the array's contents to the output. An array can be displayed in full this way.
Swift program that uses string array
// Create an empty array and add three elements to it.
var languages = [String]()
languages.append("Swift")
languages.append("Python")
languages.append("Java")
// Display count of the array.
print(languages.count)
// Print the array contents.
print(languages)
Output
3
["Swift", "Python", "Java"]
Tip: A for-in loop is clearer when we do not need to access the indexes of an array.
Swift program that uses Int array, for-in loop
// Create an Int array.
var ids = [Int]()
ids.append(10)
ids.append(20)
ids.append(50)
// Loop over and print all Ints.
for id in ids {
print(id)
}
Output
10
20
50
Tip: Please note the type Int. When reading a statement, you can say "create an array of type Int."
Swift program that uses array initializer
// Create variable Int array with three values.
var sizes: [Int] = [5, 10, 15]
// Append another Int.
sizes.append(20)
print("Sizes: \(sizes)")
Output
Sizes: [5, 10, 15, 20]
For: Swift 3 does not support the C-style for loop syntax. We can use enumerated() to get indexes and values in an elegant way.
Tip: With the index, we can access other elements in the array inside the loop body. Multiple elements can be tested in the logic.
Swift program that uses enumerated on string array
var birds = ["finch", "sparrow", "eagle"]
// Use enumerated() on the string array.
for (index, value) in birds.enumerated() {
// Display indexes and values.
print("\(index) = \(value)")
}
Output
0 = finch
1 = sparrow
2 = eagle
Var: This example would compile correctly if we were to specify "var" instead of let.
Tip: With constant let arrays, we can enforce code correctness by preventing unexpected changes to the array.
Swift program that causes error with let, append
// With let an array is constant.
// ... We cannot append to it.
let codes: [String] = ["x", "r", "w"]
codes.append("t")
Output
/Users/.../main.swift:4:1:
Immutable value of type '[String]' only has mutating members named 'append'
So: We must check the result of first and last against nil to ensure they exist. They do not exist in an empty 0-element array.
Swift program that uses first, last optionals
let cars: [String] = ["truck", "coupe", "sedan"]
// Access first and last optional elements.
// ... Test them against nil before using them.
if cars.first != nil {
print(cars.first!)
}
if cars.last != nil {
print(cars.last!)
}
Output
truck
sedan
Swift program that uses first, last indexes
// Create a String array with three elements.
let pets: [String] = ["dog", "cat", "bird"]
// Get first element.
print(pets[0])
// Get last element.
print(pets[pets.count - 1])
Output
dog
bird
Swift program that uses popLast
var names = ["bird", "fish"]
// Get last element with popLast.
if let last = names.popLast() {
print("A", last)
}
if let last = names.popLast() {
print("B", last)
}
if let last = names.popLast() {
// This is not reached, but no error is caused.
print("C", last)
}
Output
A fish
B bird
Swift program that uses isEmpty
// Create an empty birds array.
var birds: [String] = []
// The array is empty.
if birds.isEmpty {
print(true)
}
// Append an element so that the array is no longer empty.
birds.append("parrot")
if !birds.isEmpty {
print(false)
}
Output
true
false
Tip: The contains() func returns early if a match is found. This avoids processing the entire array.
Swift program that uses contains
var animals: [String] = ["bird", "frog", "elephant"]
// Determine if this string exists in the array.
if animals.contains("bird") {
print(true)
}
// This string does not exist.
if !animals.contains("diamond") {
print(false)
}
Output
true
false
Swift program that uses contains, where func
func colorStartsWithG(value: String) -> Bool {
// Check for first letter.
return value[value.startIndex] == "g"
}
func colorStartsWithX(value: String) -> Bool {
return value[value.startIndex] == "x"
}
// A simple array.
let colors = ["blue", "red", "green"]
// Simple contains.
if colors.contains("red") {
print("CONTAINS RED")
}
// Use special funcs with contains.
if colors.contains(where: colorStartsWithG) {
print("CONTAINS COLOR STARTING WITH G")
}
if !colors.contains(where: colorStartsWithX) {
print("DOES NOT CONTAIN COLOR STARTING WITH X")
}
Output
CONTAINS RED
CONTAINS COLOR STARTING WITH G
DOES NOT CONTAIN COLOR STARTING WITH X
Swift program that causes index error
let plants: [String] = ["tree", "fern", "bush"]
print(plants[999])
Output
fatal error: Array index out of range
(lldb)
Swift program that uses count, repeatedValue
// Create an array with 10,000 elements.
// ... Specify repeating and count.
var x: [Int] = Array(repeating: 0, count: 10000)
// Assign elements in array.
x[0] = 1
x[9999] = 2
x[100] = 3
// Write array contents and size.
print(x[0])
print(x[9999])
print(x[100])
print(x[1]) // Default is 0.
print(x.count)
Output
1
2
3
0
10000
Important: This does not append sub-arrays, but the individual elements. It is an "append all" syntax form.
Swift program that appends arrays
// Create an Int array.
var indexes = [10, 11, 12]
// Append three Int elements at once.
// ... The elements in the brackets are added individually.
indexes += [20, 21, 22]
// Display the result array.
for element in indexes {
print(element)
}
Output
10
11
12
20
21
22
Tip: With this style, we can use constant arrays with the let-keyword. We are not modifying array1 or array2 when we create a new array.
Swift program that adds two arrays together
// Two constant arrays with 2 elements each.
let array1 = ["cat", "bird"]
let array2 = ["fish", "plant"]
// Combine the two arrays (add them together).
let combined = array1 + array2
// Print the combined array count and elements.
print(combined.count)
print(combined)
Output
4
["cat", "bird", "fish", "plant"]
Tip: A Dictionary is a data structure that makes removal faster. In a linear array, removal often causes shifting or elements.
Here: We remove the elements at index 2 and 0. They are highlighted in the output section before removal.
Swift program that uses remove
var ids = [10, 20, 300, 5000]
print(ids)
// Remove element at index 2 (the third element, 300).
ids.remove(at: 2)
print(ids)
// Remove element at index 0 (the first element, 10).
ids.remove(at: 0)
print(ids)
Output
[10, 20, 300, 5000]
[10, 20, 5000]
[20, 5000]
Swift program that uses removeLast
var languages = ["Swift", "Java", "C#", "Go"]
print(languages)
// Remove the last element in the array.
languages.removeLast()
print(languages)
Output
["Swift", "Java", "C#", "Go"]
["Swift", "Java", "C#"]
Tip: The before and after parts do not need to have the same length. Elements are added individually, not as a sub-array.
Swift program that assigns array range
var years = [1999, 2000, 2001, 2015, 2017]
// Replace elements at indexes 0, 1 and 2.
// ... Replace 3 elements with 2 elements.
years[0...2] = [2002, 2005]
// Display result.
print(years)
Output
[2002, 2005, 2015, 2017]
Argument: The first argument to insert() is the element to insert. The second argument, specified with "at," is the target index.
Swift program that uses insert
var letters = ["A", "X", "Z"]
print(letters)
// Insert the letter C at index 1 (after the first element).
letters.insert("C", at: 1)
print(letters)
Output
["A", "X", "Z"]
["A", "C", "X", "Z"]
Here: We receive a String array in the validate func. We use a guard to ensure the first string element has a specific value.
GuardSwift program that uses string array argument
func validate(animals: [String]) {
// Test first element of string argument.
guard animals.first == "ant" else {
print("Error")
return
}
print("OK")
}
let animals = ["ant", "fish", "hamster"]
// Pass a string array as an argument.
validate(animals: animals)
Output
OK
Swift program that uses array with func
func modify(values: [Int]) {
// This func receives an array.
// ... It adds to a copy of the array.
var copy = Array(values)
copy.append(10)
copy.append(20)
copy.append(30)
print("Modify count: \(copy.count)")
}
// The array has 3 elements.
let numbers = [0, 1, 2]
print(numbers.count)
// Call the func.
modify(values: numbers)
// The array still has only 3 elements.
print("Numbers: \(numbers)")
Output
3
Modify count: 6
Numbers: [0, 1, 2]
Note: Swift since version 3 uses "index" with a first argument labeled "of" instead of an actual indexOf method.
Swift program that uses indexOf
let letters = ["aa", "bb", "cc"]
// Use index with an argument.
let index1 = letters.index(of: "bb")
let index2 = letters.index(of: "nonexistent")
print(index1)
print(index2)
// See if the string exists in the array.
// ... Use its index to print the value from the array.
if let index3 = letters.index(of: "cc") {
print(letters[index3])
}
Output
Optional(1)
nil
cc
Swift program that uses indices
let sizes = ["small", "medium", "large"]
// Get in dice so far ray.
// ... Access each element.
for i in sizes.indices {
print("\(i) / \(sizes[i])")
}
Output
0 / small
1 / medium
2 / large
Swift program that uses elementsEqual
let numbers1 = [10, 100, 2000]
let numbers2 = [10, 100, 2000]
let numbers3 = [10, 0, 2000]
// Use elementsEqual to compare entire arrays.
if numbers1.elementsEqual(numbers2) {
print("EQUAL")
}
if !numbers1.elementsEqual(numbers3) {
print("NOT EQUAL")
}
Output
EQUAL
NOT EQUAL
Swift program that uses reversed
var numbers = [10, 100, 2000]
// Reverse the numbers.
var inverted = numbers.reversed()
// Display reversed numbers.
for var pair in inverted.enumerated() {
print(pair)
}
Output
(0, 2000)
(1, 100)
(2, 10)
Here: We multiply each element in the array by 2. A copy is returned by flatMap, so the original "numbers" is unchanged.
Swift program that uses flatMap
func multiply (x: Int) -> Int {
// Multiply argument by 2 and return.
return x * 2
}
let numbers = [10, 100, 2000]
// Use flatMap on the array.
let result = numbers.flatMap(multiply)
// Before and after.
print(numbers)
print(result)
Output
[10, 100, 2000]
[20, 200, 4000]