The Problem That Generics Solve
Let’s talk about the problem that generics solve. Consider this function, which swaps two integers:
func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a = b b = temporaryA}var a = 10var b = 1swapTwoInts(&a,&b)println(a) // 1println(b) // 10
This works just as expected. You are able to swap the two Int
s by passing them as inout
parameters to the function. The problem is that this function only works with Int
s. If you try setting the variables
to 10.5
(a double) or "Hello there"
(a string), it will not work because 10.5
is a Double
and "Hello there"
is a String
. This function only takes Int
s. The function’s implementation itself (the code inside the function) ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.