Search code examples
swiftswift-playgroundgenericsswift-extensions

When to use the generic parameter clause


I'm new to generics in swift, and while reading some books, I came across something I don't understand. In generic functions, when is it appropriate to use the type parameter (the right after the function name)? and when is it inappropriate?

Here an example where it is not used (signature only; from standard library):

func sorted(isOrderedBefore: (T, T) -> Bool) -> Array<T>

Here's an example of where it is used (taken from a book I'm reading):

func emphasize<T>(inout array:[T], modification:(T) -> T) {
        for i in 0 ..< array.count {
            array[i] = modification(array[i])
        }
}

I read Apple's swift language reference, section: Generic Parameters and Arguments. But it is still not clear to me. Thanks in advance for any insight.  


Solution

  • In the first example, the generic parameter is coming from the type it is defined within. I believe it is declared within Array which already has the generic type T.

    In the second example, the function itself is declaring the generic parameter. If I am not mistaken, this function is a global function. It is not already within a scope that defines a generic T.

    It is only inappropriate to declare a new generic parameter in a function that obscures or tries to replace the one already declared in it's scope. For example, when extending an array, this would be inappropriate:

    extension Array {
        func myFunc<T>() {
        }
    }
    

    Here we are defining a new T that is obscuring the original T that is already declared in the declaration of Array.

    In all other circumstances where you want a generic type, you should be declaring it yourself.