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.swift94 chars4 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.swift107 chars4 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.
gistlibby LogSnag