Swift Programming
Xcode
iOS
Arrays
What we’ll learn:
Table of contents
📌 Update in progress
What are arrays?
Arrays are the most commonly used data types in programming. You use arrays when you want to organize a collection of values of the same data type. Values could be of any data type – from integers, strings to objects.
Syntax
var arrayName: [type] = [value, value, value]
Create an Array
Create an Empty Array
To create an empty array, specify the data type in your array declaration. We can create an array in two ways:
//option 1
var numbers: [Int] = []
// option 2
var colors = [String]()
Create an Array of String Elements
To create an array with integer elements, surround your values with an enclosing and closing bracket separated by commas.
var colors: [String] = ["blue", "green", "red"]
{ Access or Insert }
Access an Array
To access a specific element of an array, address your array name followed by a subscript with the index position of the value you want to retrieve.
Any value outside of the index rage will result in an error.
//access element at index 1
colors[1]
print(colors[1])
// prints green
Append value in an Array
appending value will be added to the end of the array
// Use the assign equals operator (+=) to append the string "purple" to the colors array.
colors += ["purple"]
The appending signature is equivalent to:
// same as the code above
colors = colors + ["purple"]
Insert Value at specific index of an Array
Use the .insert ("_", at:_)
method to insert an element at a specific index. The elements at that index are shifted to make room.
// insert "red" at index 1 (note: index starts at 0)
colors.insert("purple", at: 1)
{ Remove Value }
Remove Value in an Array
Remove Value at Specific Index
To remove elements from a specific index of an array, use the remove(at: ___)
method.
// remove value at index 1
colors.remove(at: 1)
Remove the Last Value
If you want to remove the last value of an array, use the removeLast()
method.
colors.removeLast()
{ Change Value }
Change the Value in an Array
Change Value of a Specific Index
// change the value at index 0
colors[0] = "orange"
Change Range of Values
// change a range of values
colors[1...2] = ["red", "white", "blue"]
{ Data Types }
Data Types and Properties
Common Data Types
With Swift’s type inference, the data type can be removed if default values are given.
var arrayOfInts: [Int] = [1,2,3,4,5]
var arrayOfStrings: [String] = ["here is one string", "another string", "and another"]
var arrayOfCharacters: [Character] = ["d","f", "g"]
var arrayDoubles: [Double] = [0.1, 0.22, 0.333]
var arrayBool: [Bool] = [true, false, true, true]
{ Array Properties }
Count Property
//returns number of elements in Array
colors.count
isEmpty Property
// returns true or false (boolean value)
colors.isEmpty
Contains Property
// returns a boolean value indicating whether the array contains the given element.
colors.contains("pink)