I'm wondering if there is a difference between array[0]
vs array.first?
If not which way do you prefer. I feel like array.first
is more clear, but I'm wondering if there is a difference and which way Swift programmers prefer?
Personally, I prefer using array.first
. If there are no elements in the array, the array[0]
will cause a crash, but array.first
will not. array.first
returns nil.
For array[0]
, the if !array.isEmpty {}
check should be applied first.
For array.first
, it returns an optional value, the if value == nil
check also needs to be applied after. But it's more convenient if the receiver is also optional, like UILabel
's text property: aLabel.text = array.first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With