Last time we looked at
error handling in Swift. In this article we will look at Generics and how they can make use of one set of types to define a new set of types. Let’s start with a simple Car struct.
Car is a concrete type.
On the other hand, we create the struct
Owner as a generic type and
T is its type parameter:
driver is a specialization of the generic type.
Having generics allows us to declare array in various ways:
array1 is a
array3 are representing an
Array of type
Int, so their syntax is equivalent.
Let’s look at how the
type parameter can be exploited further:
We can have the same type parameter used also as a struct member. Then creating an
Owner becomes more interesting:
Obviously, generics have
In this case
array4 becomes an
Array<Int> by type inference.
For dictionaries there is more information offered. A dictionary is a struct defined as
Dictionary<Key : Hashable, Value>. What follows after : is either a
supertype or a
protocol the key conforms to, and it is named type constraint. Dictionaries also have type inferral:
In this case, the
ages dictionary is inferred to be of
<String, Int> type.
As you might have expected,
generics work well on
So in this case we have the Optional type that can either be of Some type, or nil. Then we can test which of the two cases we need to deal with, and react accordingly:
Finally, generics can be used with functions as well. You can notice the
type parameters are the same as the
The above function call will print out as you expected:
The source code is posted on
Github, as usual.
Until next time!