Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Swift need these similar functions? Is it kind of redundant?

Tags:

swift

There are some similar methods in Swift. They look similar, actually their functions are also similar. They are:

popFirst(), popLast(), dropFirst(), dropLast(), removeFirst(), removeLast()

Especially popFirst() and removeFirst(), according to Apple doc:

func popFirst()

Removes and returns the first element of the collection.

func removeFirst()

Removes and returns the first element of the collection.

Their document descriptions are totally same. Actually I tried a lot (a whole page in playground) to see whether there are some significant differences between these methods. The answer is there are some very small differences between some methods, and some methods are totally the same according to my test.

Some methods, popFirst(), popLast() and dropLast(), dropFirst() are different when used on String and Array. But according to my test, they all can be replaced by removeFirst() and removeLast() (despite there are some tiny differences).

So my question is why Swift has to keep these similar methods. Is it kind of redundant?

like image 847
JW.ZG Avatar asked Oct 29 '22 19:10

JW.ZG


1 Answers

Although Apple did not make it easy to find, it does mention that pop returns nil for an empty collection, and that remove throws an error when there is nothing to remove.

However, you should be able to tell the same from the signatures of these functions:

  • popFirst returns an optional, which implies that you can pop first element even from an empty collection
  • removeFirst, on the other hand, is not optional. Signatures like that imply that it is an error to call this method in a state when it cannot return a value.

This could be easily confirmed using a playground:

var test1 = Set<String>(["a", "b"])
let x1 = test1.popFirst()
let y1 = test1.popFirst()
let z1 = test1.popFirst()            // returns nil
var test2 = Set<String>(["a", "b"])
let x2 = test2.removeFirst()
let y2 = test2.removeFirst()
let z2 = test2.removeFirst()         // Throws an error
like image 167
Sergey Kalinichenko Avatar answered Nov 15 '22 06:11

Sergey Kalinichenko