find the last element in an array in swift

To find the last element in an array in Swift, you can use the built-in last property of Array. Here's an example:

main.swift
let myArray = [1, 2, 3, 4, 5]
let lastElement = myArray.last
print(lastElement!) // Output: 5
94 chars
4 lines

In the code above, the last property of myArray returns an Optional value, so we use the ! operator to force unwrap the value.

Alternatively, you can use subscript syntax to access the last element directly by using the array's count property to subtract 1 from the index, like so:

main.swift
let myArray = [1, 2, 3, 4, 5]
let lastElement = myArray[myArray.count - 1]
print(lastElement) // Output: 5
107 chars
4 lines

However, using the last property is generally a safer and more convenient way to access the last element of an array, as it handles cases where the array might be empty.

related categories

gistlibby LogSnag