Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between array[0] vs array.first?

Tags:

swift

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?

like image 675
PictureMeAndYou Avatar asked Feb 04 '23 15:02

PictureMeAndYou


1 Answers

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

like image 88
Yun CHEN Avatar answered Feb 07 '23 17:02

Yun CHEN