Generics in
Swift
IOS Mobile App Development In swift, Generics are the
parameterized types. By using generics, we can write clear, flexible and
reusable functions. It allows us to avoid duplication of functions, and lets we
write our code in a clear and expressive manner. Swift is a strong-typed
language and that means that when we define a type for a variable – we always
must do that – we can’t change it later. Neither can this variable contain
different types, because it can only have one type. With generics we can
specify a “generic type” – a type that’s loosely defined and for instance
constrained by its relation to other variable types. Generally, in swift by
using generics we can avoid a duplicate code by writing a reusable functions or
methods in a clear and abstracted manner based on our requirements.
The concept of generics is powerful in
swift and the standard libraries like arrays or dictionaries of swift built by
using generic code. In swift, when we create an array, it can hold any type of
data like integer, string or any other types same way dictionaries are
also used to hold any type of data as a key value pair.
The simple non-generic function example
which shows how generics will help in swift programming
language.
In above example we defined a two functions intValueSwap,
stringValueSwap to swap integers and strings separately because intValueSwap
function will work only for Integers value and stringValueSwap function will
work only for Strings. So, if we use non-generic code we need to create a separate
methods or functions based on the type of data due to that redundant code will
increase in application.
Generic
Functions
We define a generic function by using angle brackets with a
type placeholder after the function name. The convention is for this
placeholder to be called T.
In this example we define a function that does nothing
except return the parameter that is passed to it. By adding <T> after the
function name we’ve indicated that this is a generic function and that used T
as a placeholder for the type. In the functions type signature, we have
indicated that it takes a parameter called x of type T and returns something of
type T.
We can call this function with an integer, Double or a
string and it works with either one.
Now we will implement a generic version for
the above example which we used to swap integers and strings.
The example of using generics to avoid a redundant code in swift
programming language.
Conclusion
That’s
it. So far we have covered the basics of generics and generic functions, In the
next blog we will cover Generic as a type, Extension, Associated type and
generic with where clause so on.
Author
Pankaj Ray
Canarys Automations PVT LTD
No comments:
Post a Comment