Don't understand multiple parameter declarations in objective-c

can someone clarify this for me:

If for multiple arguments the arguments are declared in the method name after the colons. Arguments break the name in the declaration, as in the message. For instance:

- (void)setWidth:(float)width height:(float)height; 

So in the example above:

  • a method is, for example, variables
  • returns void
  • parameter # 1 is a float named width.
  • parameter # 2 is a float called height.

But why is it hieght: (float) height; not only:

 - (void)setWidth: (float)width (float)height; 
+4
source share
3 answers

Objective-C has no named arguments . There are also no "keyword arguments".

Objective-C uses what are called "alternating arguments." That is, the name of the method alternates with the arguments to get a more descriptive and readable code.

 [myObject setWidth:w height:h]; 

In the above description, it is generally reported that myObject sets the width w and the height to h.

In the above case, the method name - its selector - is exactly setWidth:height: No more no less.

All this is explained in the Objective-C guide .

+6
source

This is just an Objective-C function to make your life easier when reading a method call, which will look like this:

 [myObject setWidth:w height:h]; 

You can leave labels (except for the first), so if you really want to, you can:

 -(void)setWidth:(float)width :(float)height { ... } 

and use it like:

 [myObject setWidth:w :h]; 

But this is not quite in the spirit of the Objective-C language. The whole point of these shortcuts is to make these calls more understandable without having to look for a method definition.

+2
source

The fact that the argument name is also part of the method name is confusing. Think about what you actually call it:

 [something setWidth:500 height:250]; 

Following your suggestion, it will be something like this:

 [something setWidth:500 250]; // That 250 is just kind of hanging // out there — not very readable 

You can also give the argument a completely different name from that part of the method name that precedes it:

 - (void)setGivenName:(NSString *)first surname:(NSString *)last 
+1
source

Source: https://habr.com/ru/post/1312606/


All Articles