Native Shopify Mobile App with 20 new features
Kickstart your hyperlocal marketplace in Corona pandemic with a starter guide
Android App Development
iOS App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 126.96.36.199 release ready!
Owner and Founder. Opencart
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.
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 (Int, String, 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 Int, String, 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.
So if you have any comments, questions, or recommendations, feel free to post them in the comment section below!
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.