Array by Example - Swift Programming Language

Overview

  • An ordered, random-access collection.
  • you use the Array type to hold elements of a single type, the array’s Element type. An array can store any kind of elements—from integers to strings to classes.

1. Creating and Initializing an Array

1.1 Creating an Array

  • Swift makes it easy to create arrays in your code using an array literal: simply surround a comma separated list of values with square brackets.
  • Without any other information, Swift creates an array that includes the specified values, automatically inferring the array’s Element type.
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
print(oddNumbers)

//prints [1, 3, 5, 7, 9, 11, 13, 15]

let streets = ["Albemarle", "Brandywine", "Chesapeake"]
print(streets)

//prints ["Albemarle", "Brandywine", "Chesapeake"]

1.2 init(repeating:count:)

  • Creates a new array containing the specified number of a single, repeated value.
let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
//prints ["Z", "Z", "Z", "Z", "Z"]

1.3 init(_:)

  • Creates an array containing the elements of a sequence.
let numbers = Array(1...7)
print(numbers)

//prints [1, 2, 3, 4, 5, 6, 7]

1.4 init()

  • Creates a new, empty array.
var emptyArray = Array<Int>()
print(emptyArray.isEmpty)

// Prints "true"

emptyArray = []
print(emptyArray.isEmpty)

// Prints "true"

2. Inspecting an Array

2.1 isEmpty

  • A Boolean value indicating whether the collection is empty.
let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}

// Prints "Hi ho, Silver!")

2.2 count

  • The number of elements in the array.
let numbers = Array(1...7)
print("Count of number array is \(numbers.count)")

//prints Count of number array is 7

2.3 capacity

  • The total number of elements that the array can contain without allocating new storage.
let numbers = Array(1...7)
print("Capacity of number array is \(numbers.capacity)")

//prints Capacity of number array is 7

3. Accessing Elements

3.1 subscript(_:)

  • Accesses the element at the specified position.
var streetsArray = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
streetsArray[1] = "Butler"
print("Subscript 1 is \(streetsArray[1])")

//prints Subscript 1 is Butler

3.2 first

  • The first element of the collection.
let numberArray = [10, 20, 30, 40, 50]
if let firstNumber = numberArray.first {
    print("FirstNumber is \(firstNumber)")
}

//prints FirstNumber is 10

3.3 last

  • The last element of the collection.
if let lastNumber = numberArray.last {
    print("Last number in array is \(lastNumber)")
}

//prints Last number in array is 50

3.4 subscript(_:)

  • Accesses a contiguous subrange of the array’s elements.
let streetArr = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streetArr[2 ..< streetArr.endIndex]
print(streetsSlice)

// prints ["Channing", "Douglas", "Evarts"]

let i = streetsSlice.index(of: "Evarts")print(streetArr[i!])

//prints Evarts

4. Adding Elements

4.1 append(_:)

  • Adds a new element at the end of the array.
var numberArray1 = [1, 2, 3, 4, 5]
numberArray1.append(100)
print(numberArray1)

//prints [1, 2, 3, 4, 5, 100]

4.2 append(contentsOf:)

  • Adds the elements of a sequence or collection to the end of this collection.
var numbers = [1, 2, 3, 4, 5]
numbers.append(contentsOf: 10...15)
print(numbers)

// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"

4.3 insert(_:at:)

  • Inserts a new element at the specified position.
numberArray1.insert(100, at: 3)
numberArray1.insert(200, at: numberArray1.endIndex)
print(numberArray1)

//prints [1, 2, 3, 100, 4, 5, 100, 10, 11, 12, 13, 14, 15, 200]

4.4 insert(contentsOf:at:)

  • Inserts the elements of a sequence into the collection at the specified position.
numberArray1.insert(contentsOf: 100...103, at: 3)
print(numberArray1)
//prints [1, 2, 3, 100, 101, 102, 103, 100, 4, 5, 100, 10, 11, 12, 13, 14, 15, 200]

4.5 replaceSubrange(_:with:)

  • Replaces a range of elements with the elements in the specified collection.
 var nums = [10, 20, 30, 40, 50]
 nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
 print(nums)

 //prints [10, 1, 1, 1, 1, 1, 50]

4.6 reserveCapacity(_:)

  • Reserves enough space to store the specified number of elements.
var values: [Int] = [0, 1, 2, 3]

   func addTenQuadratic() {
      let newCount = values.count + 10
      values.reserveCapacity(newCount)
      for n in values.count..<newCount {
          values.append(n)
      }
  }
print(values)

//prints [0, 1, 2, 3]

5. Removing Elements

5.1 remove(at:)

  • Removes and returns the element at the specified position.
var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
let removed = measurements.remove(at: 2)
print(measurements)

//prints [1.1000000000000001, 1.5, 1.2, 1.5, 1.3, 1.2]

5.2 removeFirst(_:)

  • Removes the specified number of elements from the beginning of the collection.
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst(3)
print(bugs)

//prints ["Damselfly", "Earwig"]

5.3 removeLast(_:)

  • Removes the specified number of elements from the end of the collection.
bugs.removeLast(1)
print(bugs)

//prints ["Damselfly"]

5.4 removeSubrange(_:)

  • Removes the elements in the specified subrange from the collection.
var measurements1 = [1.2, 1.5, 2.9, 1.2, 1.5]
measurements1.removeSubrange(1..<4)
print(measurements1)

//prints [1.2, 1.5]

5.5 removeAll())

  • Removes all elements from the collection.
measurements1.removeAll()
print(measurements1)

//prints []

6. Finding Elements

6.1 contains(where:)

  • Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
enum HTTPResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        return true
    } else {
        return false
    }
}
print(hadError)

//prints true 

6.2 first(where:)

  • Returns the first element of the sequence that satisfies the given predicate.
let numbers1 = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers1.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}

//prints The first negative number is -2.

6.3 index(of:)

  • Returns the first index where the specified value appears in the collection.
var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.index(of: "Maxime") {
    students[i] = "Max"
}
print(students)

//prints ["Ben", "Ivy", "Jordell", "Max"]

6.4 min()

  • Returns the minimum element in the sequence.
let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let lowestHeight = heights.min()
print(lowestHeight ?? "none")

//prints 58.5

6.5 min(by:)

  • Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue!)

//prints (key: "Coral", value: 16)

6.6 max()

  • Returns the maximum element in the sequence.
let greatestHeight = heights.max()
print(greatestHeight!)

//67.5

6.7 max(by:)

  • Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
let greatestHue1 = hues.max { a, b in a.value < b.value }
print(greatestHue1!)

//prints (key: "Heliotrope", value: 296)

7. Selecting Elements

7.1 prefix(_:)

  • Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.
let numbersA = [1, 2, 3, 4, 5]
print(numbersA.prefix(2))

//prints [1, 2]

7.2 prefix(through:)

  • Returns a subsequence from the start of the collection through the specified position.
let numbersAr = [10, 20, 30, 40, 50, 60]
if let i = numbersAr.index(of: 40) {
    print(numbersAr.prefix(through: i))
}

//prints [10, 20, 30, 40]

7.3 suffix(_:)

  • Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
let numbersA = [1, 2, 3, 4, 5]
print(numbersA.suffix(2))

//prints [4, 5]

7.4 suffix(from:)

  • Returns a subsequence from the specified position to the end of the collection.
let numbersS = [10, 20, 30, 40, 50, 60]
if let i = numbersS.index(of: 40) {
    print(numbersS.suffix(from: i))
}

//prints [40, 50, 60]

8. Iterating Over an Array's Elements

8.1 forEach(_:)

  • Calls the given closure on each element in the sequence in the same order as a for-in loop.
let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}

//prints one
two
three

8.2 enumerated()

  • Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.
for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}

//prints 
0: 'S'
1: 'w'
2: 'i'
3: 'f'
4: 't'

9. Sorting an Array

9.1 sort()

  • Sorts the collection in place.
var students1 = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students1.sort()
print(students1)

//prints ["Abena", "Akosua", "Kofi", "Kweku", "Peter"]

9.2 sort(by:)

  • Sorts the collection in place, using the given predicate as the comparison between elements.
enum HTTPResponse1 {
    case ok
    case error(Int)
}

var responses: [HTTPResponse1] = [.error(500), .ok, .ok, .error(404), .error(403)]
responses.sort {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode

    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false

    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(responses)

//prints [TempCode.HTTPResponse1.error(403), TempCode.HTTPResponse1.error(404), TempCode.HTTPResponse1.error(500), TempCode.HTTPResponse1.ok, TempCode.HTTPResponse1.ok]

9.3 sorted()

  • Returns the elements of the collection, sorted.
let studentsT: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = studentsT.sorted()
print(sortedStudents)

//prints ["Abena", "Akosua", "Kofi", "Kweku", "Peter"]

9.4 reversed()

  • Returns a view presenting the elements of the collection in reverse order.
let numbersC = [3, 5, 7]
for number in numbersC.reversed() {
    print(number)

//prints 7
5
3

10. Excluding Elements

10.1 dropFirst()

  • Returns a subsequence containing all but the first element of the sequence.
let numbersW = [1, 2, 3, 4, 5]
print(numbersW.dropFirst())

//prints [2, 3, 4, 5]

10.2 dropLast()

  • Returns a subsequence containing all but the last element of the sequence.
let numbersW = [1, 2, 3, 4, 5]
print(numbersW.dropLast())

//prints [1, 2, 3, 4]

11. Manipulating Indices

11.1 startIndex

  • The position of the first element in a nonempty array.
print(numbersW.startIndex)

//prints 0

11.2 endIndex

  • The array’s “past the end” position—that is, the position one greater than the last valid subscript argument.
print(numbersW.endIndex)

//prints 5

12. Splitting and Joining Elements

12.1 split(separator:maxSplits:omittingEmptySubsequences:)

  • Returns the longest possible subsequences of the sequence, in order, around elements equal to the given element.
let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " ") .map(String.init))

//prints ["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]

12.2 split(maxSplits:omittingEmptySubsequences:whereSeparator:)

  • Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.
print(line.split(whereSeparator: { $0 == "a" }))

//prints ["BLANCHE:   I don\'t w", "nt re", "lism. I w", "nt m", "gic!"]

12.3 joined(separator:)

  • Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let list = cast.joined(separator: ", ")
print(list)

//prints Vivien, Marlon, Kim, Karl

12.4 joined()

  • Returns the elements of this collection of collections, concatenated.
let ranges = [0..<3, 8..<10, 15..<17]
for range in ranges {
  print(range)
}
// Prints "0..<3"
// Prints "8..<10"
// Prints "15..<17"

for index in ranges.joined() {
    print(index, terminator: " ")
}

// Prints: "0 1 2 8 9 15 16"

13. Comparing Arrays

13.1 ==(_: _:)

  • Returns true if these arrays contain the same elements.
let arr1 = [1, 2, 2, 3, 4, 5]
let arr2 = [1, 3, 6, 7, 9 ,10] 
if (arr1 == arr2){
	print("EQUAL ARRAY\(arr1)")
}else{
	print("NOT EQUAL")
}

//prints NOT EQUAL 

13.2 !=(::)

  • Returns true if the arrays do not contain the same elements.
let arr1 = [1, 2, 2, 3, 4, 5]
let arr2 = [1, 3, 6, 7, 9 ,10] 
if (arr1 != arr2){
	print("Not EQUAL")
}else{
	print("EQUAL")
}

//prints Not EQUAL

13.3 elementsEqual(_:)

  • Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.
if (arr1.elementsEqual(arr2)){
	print("equal elements")
}else{
	print("Not equal")
}

//prints Not equal

13.4 starts(with:)

  • Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.
let a = 1...3
let b = 1...10
print(b.starts(with: a))

//prints true

13.5 lexicographicallyPrecedes(_:)

  • Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.
let a = [1, 2, 2, 2]
let b = [1, 2, 3, 4]
print(a.lexicographicallyPrecedes(b))

// Prints "true"

print(b.lexicographicallyPrecedes(b))

// Prints "false"

14. Describing an Array

14.1 description

  • A textual representation of the array and its elements.
let ax = [1, 2, 2, 2]
print(ax.description)

//prints [1, 2, 2, 2]

14.2 debugDescription

  • A textual representation of the array and its elements, suitable for debugging.
let ax = [1, 2, 2, 2]
print(ax.debugDescription)

//prints [1, 2, 2, 2]

14.3 customMirror

  • A mirror that reflects the array.
let ax = [1, 2, 2, 2]
print(ax.customMirror)

//prints Mirror for Array<Int>

15. Bridging Between Array and NSArray

  • When you need to access APIs that require data in an NSArray instance instead of Array, use the type-cast operator (as) to bridge your instance.

  • For bridging to be possible, the Element type of your array must be a class, an @objc protocol (a protocol imported from Objective-C or marked with the @objc attribute), or a type that bridges to a Foundation type.


import Foundation
var arr : NSMutableArray = ["Pencil", "Eraser", "Notebook"]

func bar (a : NSMutableArray)
{
    a[2] = "Pen"
}

bar(a : arr)

print (Array(arr))

//prints ["Pencil", "Eraser", "Pen"]

You can download the swift playground of all above examples from Here




Related Article