One of the most intriguing aspects of Objective-C is the use of [ square brackets ], which left everyone wondering about the story behind this interesting notation
They may resemble arrays, but they are actually used to send messages. What?!
Objective-C was inspired by a language called Smalltalk for the OOP (Object-Oriented Programming) part. The idea behind Smalltalk was to send messages as we do in real life.
Well, if in the real life, we can say something like that:
And in Smalltalk we would say:
Bear in mind that in Smalltalk everything is an object, thus you can send the following messages to this object. In our example, ovidiu is an object. Well, I’m not really an object but let’s say so for the sake of this example :))
So, the inventors of Objective-C (Brad Cox and Tom Love) thought that enclosing messages in square brackets would make the parser faster and the code easier to understand.
Like this:
The C++, Java or C# equivalent would be:
You see the difference? They did not think about messages as functions, but something more “natural”!
Today, we have become so familiar with the “.” and “()” syntax used in Java and C++ that we hardly notice how “unnatural” they might be in reality…
Of course, methods in Objective-C can return values, and also receive parameters. Let’s go back to that “ovidiu” object.
In C++ we would have something like this:
This feels quite unnatural, don’t you think? Here’s the equivalent implementation in Objective-C:
So, the weird syntax doesn’t look so weird now, right?
As with everything in life, just because something gained popularity doesn’t mean that it is the best.