first property in Swift Array
In this article we are going to see the importance of first
property in Array Collection.
The value of the property is the first element of the collection. If the collection is empty, the value of this property is nil
.
Example:
let array = [1,2,3]
let element = array.first
The value of element
is 1.
Benefits of using first property instead of array[0]
first property is optional, it means that it’s value can be nil. Consider the below function.
func getFirstElement(array: [Int]?) -> Int? {
return array?[0]
}
Consider an empty array
let array: [Int]? = []
Let us pass this array into the above function and see what happens
print(getFirstElement(array: array1))
OOPS! The app crashed. This is because the 0th index does not exists as the array is empty. We need to return nil in this case. Let us modify our function
func getFirstElement(array: [Int]?) -> Int? {
if let array = array, array.count > 0 {
return array[0]
} else {
return nil
}
}
This looks so lengthy and complicated for a basic functionality. first property is the solution to make it short and sweet.
func getFirstElementUsingFirst(array: [Int]?) -> Int? {
return array?.first
}
The above function works in every case.
If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!