Game Development Reference
In-Depth Information
It's pretty straightforward, but what if you wanted to compare
String
s? You would have
to write a whole new function. Generics solve this problem. Generics have the following
syntax:
func functionName
<T>
(param :
T
)
The definition starts normally enough. The differences start after the function name. Here
you have a
T
surrounded by less-than and greater-than signs,
<T>
. This
T
represents a
generic type that will be determined by the type passed to this function at the parameter
position where there is a
T
. If you passed an
Int
in this position, then wherever a
T
was
found in the function definition, the compiler would expect another
Int
. The compiler
would see something like this:
func functionName
<Int>
(param :
Int
)
If you wanted to pass in two params of different types, you would have the following
definition:
func functionName
<T, G>
(param :
T,
param2 :
G
)
And if you wanted to return the same type, you add a generic return definition to your
function.
func functionName
<T>
(param :
T
) ->
T
Finally, if you wanted to restrict the types that could be represented by the generic, you
would add a
where
clause.
func functionName
<T where T: type>
(param :
T
) ->
T
The type in the
where
clause can force the type to implement a protocol, require two
types to be the same, or even require a class to have a particular superclass. Let's look at
some code that will make this a little clearer: Take a look at the following code:
func orderTwoValuesAscending<
G where G: Comparable
>(val1:
G
, val2:
G
)
-> (lesser:
G
, greater :
G
) {
if val1 > val2 {
return (val2, val1)
}