Ihor Bats
Ihor Bats

Reputation: 169

Why swift protocol use func overloading instead on func with different names?

Just started to learn swift and noticed that protocol UICollectionViewDelegate (https://developer.apple.com/documentation/uikit/uicollectionviewdelegate) has around 20 functions with the same name but different parameters. In C# we use overloads as well but we use them in case we want to do something similar like:

but in swift we use the same func name for functions that do absolutely different things like:

So the question is, why they don't use funcs like:

in this case func name actually tells us what it's going to do and it's easier to find function you need

If there is some documentation why such a decisions were made I would really appreciate it.

Thank you

Upvotes: 2

Views: 661

Answers (2)

Yuji
Yuji

Reputation: 166

It has something to do with how Objective C work, if you write these functions as selectors, it will be something like "collectionView:didSelectItemAt:". Which implicitly tell you that it has something to do with collectionView, and won't confuse with "tableView:didSelectItemAt:".

On the other hand if the function named "didSelect:itemAt:", it does not provide any hints on what's the first parameter, it can be tableView, collectionView, or anything else, since objective c does not support overload, this will become a problem.

Upvotes: 1

Donovan King
Donovan King

Reputation: 855

So in swift the function name is actually broken up to be next to each param that the name is describing. This convention has it's roots in objective-c.

So those functions you showed above actually do have different names, the names is just broken up.

So

collectionView(UICollectionView, didSelectItemAt: IndexPath)

is collectionView:didSelectItemAt:

func collectionView(UICollectionView, targetContentOffsetForProposedContentOffset: CGPoint)

is collectionView:_ targetContentOffsetForProposedContentOffset:_

It's a very descriptive naming convention. Just remember that the function's name is split up to be next to each parameter that the piece of the name is describing.

Upvotes: 1

Related Questions