What is the difference between func (to view: UIView) and not using the 'to'?

I have a function in my UIView extension and I can call it both ways

This way:

func anchorSizePercent(to view: UIView, sFactor: CGSize) {
...
 }

myHeader.anchorSizePercent(to: myView, sFactor: CGSize(width: 0.8, height: 0.2))

As well, I can call it without the to, such as:

func anchorSizePercent(view: UIView, sFactor: CGSize) {
...
 }

myHeader.anchorSizePercent(view: myView, sFactor: CGSize(width: 0.8, height: 0.2))

May I ask what the difference is?

Answered by Claude31 in 707563022

there is no difference as far as operations are concerned

Yes, there is no difference. Just take care not to create 2 different func because signature is slightly different.

(to view: UIView,
  • ..."to" is used when calling the func
  • "view" is used inside the func
(view: UIView,
  • "view" is used both when calling the func, and inside the func

So it is a stylistic thing... it may be preferable to think of anchoring "to" something.
But inside a func body, "to" is pretty meaningless, so we replace it with "view".

to is a label to make code more readable.

Both behave exactly the same.

But,

  • from outside perspective (the caller), first form is more understandable: I know view is the view I go to.
  • from inside (in the func) perspective, referencing view is more meaningful than using to.

That's why the label is different from the parameter.

Second form is equivalent to

func anchorSizePercent(view view: UIView, sFactor: CGSize) {

Note that the 2 forms are different func (signature is different). So you can have both in code, there will not be a compiler error. So important to know which you call.

func anchorSizePercent(to view: UIView, sFactor: CGSize) {
   print("with to label")
 }

func anchorSizePercent(view: UIView, sFactor: CGSize) {
   print("without label")
 }

if you call

myHeader.anchorSizePercent(to: myView, sFactor: CGSize(width: 0.8, height: 0.2))
myHeader.anchorSizePercent(view: myView, sFactor: CGSize(width: 0.8, height: 0.2))

you will get in log:

  • with to label
  • without label
Accepted Answer

there is no difference as far as operations are concerned

Yes, there is no difference. Just take care not to create 2 different func because signature is slightly different.

What is the difference between func (to view: UIView) and not using the 'to'?
 
 
Q