Leveraging Operator Overloading to construct a custom operator to ease iPhone iPad app development
I would recommend you to go through the Operator Overloading article, which I have written before reading through this article. We need to have our foundation knowledge on Operator Overloading before reading through this article.
I have seen many people writing the same boilerplate check code for managing the iPhone and iPad by writing either a
ternary operator or an
if block. Instead of this, we can easily implement the differentiator using a custom operator.
For this, we will be needing
For all Custom infix operators, it belongs to a precedence group. A precedence group specifies an operator’s precedence relative to other infix operators, as well as the operator’s associativity.
<> is an operating operator collection. And the precedence of it is unordered because it can take
AssignmentPrecedence. Thus we are specifying the
higherThan value as
assignment When set to
true, an operator in the corresponding precedence group uses the same grouping rules during optional chaining as the assignment operators from the standard library. Otherwise, when set to
false or omitted, operators in the precedence group follow the same optional chaining rules as operators that don’t perform an assignment.
testing?.number ++ 5 is the operation which we are performing with the
++ operator. If we have given the assignment as false we will get an error and if we have given the assignment as true then it will give us a value
Optional(previousValue + 5)
Now we will fix
<> in the
IdiomPrecedence to make it assignable during optional chaining with the assignment value set as true.
infix operator <>: IdiomPrecedence
Now we will add a function for the
Now we can easily consume this operator
<> To differentiate or assignment specific values to iPhone-iPad like the below code.
nameLbl.font = UIFont.systemFont(ofSize: 20) <> UIFont.systemFont(ofSize: 35)
nameLbl will be set with a fontSize of 20 in case of iPhone and 35 in case of iPad. In the same way you can consume the
<> operator for differentiator assignments in multiple ways.
I hope you have understood how we can use a custom operator to set iPhone iPad setters. Below is the project link for the same.
If you like this story, please share and follow my account for more stories like these. Do let me know if you have any queries or suggestions. Thanks for reading ❤️