Honey Honey - 2 months ago 6
Swift Question

What do we need to define placeholder data type for generics?

func inspect <SomeType> (value: SomeType) {
print ("Received \(type(of: value)) with the value of \(value)")
}


I am following a tutorial from Pro Swift book, but I can't understand why do we need the
<SomeType>
. It seems unnecessary. What added information are we giving to the compiler?

The author himself says:


Note the use SomeType: there's one in angle brackets directly after
the function name, and one to describe the value parameter. The first
one in the angle brackets is the most important, because it defines
your placeholder data type: inspect() means "there's a
function called inspect() that can be used with any sort of data type,
but regardless of what data type is used I want to refer to it as
SomeType." So, the parameter value: SomeType should now make more
sense: SomeType will be replaced with whatever data type is used to
call the function.


I don't get it nor understand what does placeholder data types means?

Answer

It may be confusing because that function is not a very good example of generics. That function could be rewritten as a non-generic and still do exactly the same thing:

func inspect (value: Any) {
    print ("Received \(type(of: value)) with the value of \(value)")
}

They become more useful in other cases. For example, if it were something like

func inspect <T> (value1: T, value2: T) {
    // ....
}

That tells the compiler that T can be any type, but that the two arguments must be of the same type. If you had used Any here, the arguments could be any type and could be of different types.

Or maybe

func inspect <T> (value:T) -> T {
    // ....
}

That says that the function takes an argument of any type and returns something of the same type. Again, if you used Any here, the declaration wouldn't require that the return type match the argument type.