Constrained Extension in Swift with Arrays

Vishwas Ng
4 min readApr 12, 2018

--

Protocol and Extensions are an integral part of the swift development. You might have used it a lot of time by now. you might have created an Extension for your class or for your Structs for different reasons.

Here I am going to give few examples where you can have extensions for few existing class.If you guys remember working on Objective-C then you would have cross-path with Catagories.

Here Constrained Extension is a type of category where you will extend the functionality of the existing object even without knowing their internal working.

Here I am going to take an example of Array, Array is a collection of homogenous elements, Where when working on a real-time project you need to work on a lot of Arrays where this need to be manipulated constantly you can come up with extensions for same

Array With Strings

let’s take a hypothetical scenario where you have an array of the string and need to have few data beforehand like

  • TotalCharacterCount
  • Word Count
  • Number of Character in each Word

let’s take an array example as below

let arrayString:[String] = [“The Godfather” , “The Shawshank Redemption” , “Schindler’s List” , “Raging Bull” , “Gone with the Wind” , “The Wizard of Oz” , “Lawrence of Arabia” , “ Forrest Gump”]

Now assume you have this kind of array across the project were the same implementation as above needed.

In order to avoid duplicity and also to extend the capability of existing Array, we can write extension as below

In above code, Array extensions work only for String Array. Here where the constrained extension come into the play. If u try to use above methods with Array of other kinds you will get an error

By implementing the constrained Extension on Array you can easily avoid the duplicate of the code and Array manipulation can be easy.

Let us go ahead and test implementation

let characterCount = arrayString.totalCharacterCount()
let wordCount = arrayString.wordCount()
let eachCharacterCount = arrayString.elementCharacterCount()
print(“characterCount = \(characterCount)”)
print(“wordCount = \(wordCount)”)
print(“eachCharacterCount = \(eachCharacterCount)”)
// this will printcharacterCount = 128
wordCount = 22
eachCharacterCount = [13, 24, 16, 11, 18, 16, 18, 12]

Here another example with Numbers

Here another example of Array with Numbers

Here in above sample am taking an example for calculating

  • Sum of array elements
  • Convert the Numerical array to String Array

This works seamlessly on Any numeric array but again error on other elements in an array.

let numArray = [1,2,3,4,5,6]
print("numArrayType = \(type(of: numArray))")
let sumValue = numArray.sum()
let convertedStringArray = numArray.string()
print("val = \(sumValue)")
print("convertedStringArray = \(convertedStringArray)")
print("convertedStringArrayType = \(type(of: convertedStringArray))")
// The printed Values are
numArrayType = Array<Int>
val = 21
convertedStringArray = ["1", "2", "3", "4", "5", "6"]
convertedStringArrayType = Array<String>

The Extensions are not limited to Swift elements like Strings and numbers, It can also be extended for user-defined objects.

consider code

Here we have a Person Struct where his name, age and salary details can be defined.Let us go ahead and create a different person and add in an Array.

The above code will print

Person-Age :- 40
Person-Age :- 45
Person-Age :- 30
Person-Age :- 28
Person-Age :- 50

Now you want to Rearrange Array based on

  • salary
  • Age

you can easily do as below Extension

then you can easily implement the code to re-arrange Array element as

The expected result will be rearranged as

Person-Rearranged-Age :- 50
Person-Rearranged-Age :- 45
Person-Rearranged-Age :- 40
Person-Rearranged-Age :- 30
Person-Rearranged-Age :- 28
Person-Rearranged-Salary :- 932.0
Person-Rearranged-Salary :- 1527.0
Person-Rearranged-Salary :- 1763.0
Person-Rearranged-Salary :- 1876.0
Person-Rearranged-Salary :- 13344.0

As stated above constrained extension come in handy when manipulating array contents. Also, avoid duplication of code.

These extensions are not restricted to above Example and can be used differently for different purpose.

Just one last example.

The above code calculates the number of occurrence of individual character and returns the value as a dictionary.

let stringArray = [“Vishwas” ,”Palindrome” , “Rat”]
let char:[Character] = stringArray.flatMap{Array($0)}
let repeatDict = char.characterCount()
print(repeatDict)
// The above code will print["V": 1, "w": 1, "n": 1, "o": 1, "d": 1, "t": 1, "a": 3, "i": 2, "r": 1, "m": 1, "R": 1, "s": 2, "e": 1, "l": 1, "P": 1, "h": 1]

you can find a complete playground below

P.S :- If you want to know more about the function “Map” , “Reduce”, “Sort” which is used in code ,you can refer to my other Article about Higher order functions

--

--