Wednesday, May 2, 2018

Swift Constrained Extensions


Extension are used to add new functionalities.

  1. An extension can be written on NSArray to remove duplicates.
  2. An extension can be written on NSString to remove unwanted words.
  3. An extension can be written on NSDictionary to remove all null values.


Like this, Not only for Native classes but also for custom classes we can very well write the Extensions.

This sounds interesting and very useful until you come across a scenario where you need extension only for specific type.

Let’s say, We have an array where we need to write an extension to check whether it contains a string or not in it. This is pretty simple, but what If that array can have Ints/Strings/Dictionaries?

So, Here, Based on the type of elements an array is having, we need to write separate extensions for NSArray.











stringArr containsKey goes to Element == String constrained extension as this array is having all strings in it. Where as, intArr containsKey goes to Element: Numeric constrained extension.
Keep a breakpoint and check which array extension is getting called.

That is how constrained extensions are very useful to route logic based on the Elements type in an array.

Here, you might have observed like for String I have given,

Element == String

&

for Ints and Floats, I have given,

Element: Numeric





There is a point here to be discussed.

Element == String, Element should be of String type.
Element: Numeric, Element should confirm to Numeric protocol

That is the reason, intArr and floatArr are going to Numeric constrained extension.



Hope this post is useful. Feel free to comment incase of any queries.

No comments:

Post a Comment