Generics in Swift

Updated 1 November 2020

Save

Generics provides the powerful features to write flexible, reusable functions, remove bulky code and work with any type. Here, we can remove duplication of the code of different data types in an abstracted manner. In Swift, Array and Dictionary are of the generic type. Both store Int values, String values, Double values, Float values, Bool values which you want.

 

Why We Used Generics

Let’s compare normal and generic functions. Normal function example:

 

You have noticed that the bodies of the stringFunc(_:, _:), doubleFunc(_:, _:), intFunc(_:, _:), and arrayDictFunc(_:, _:) functions may work identically, but then there is the only difference of types of values The only difference is the type of the values that they accept (IntString, and Double).

It will be more helpful if we write a single function to replace all normal functions and work for every type of value in a single function.

For this, swift introduce the Generics to provide powerful functionality and more flexibility in the coding. Generic function example:

The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as IntString, or Double). The placeholder type name doesn’t say anything about what T must be, but it does say that both a and b must be of the same type T, whatever T represents. The actual type to use in place of T is determined each time.

And T is inferred to be different types as:

If the generic function has two or more different parameter in the same function then we used different placeholder like,

T and K can infer to different types as:

Generics are at the core of many common language features, such as arrays and dictionaries. It is an integral feature that you’ll use every day to write powerful and type-safe abstractions.

Conclusion

So if you have any comments, questions, or recommendations, feel free to post them in the comment section below!

 

…..

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home