PictureMeAndYou
PictureMeAndYou

Reputation: 533

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

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?

Upvotes: 6

Views: 2195

Answers (1)

Yun CHEN
Yun CHEN

Reputation: 6648

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

Upvotes: 9

Related Questions