concept generic function in category swift

appears as: generic functions, generic function, The generic function
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

In Swift, generics and protocols are vital in creating polymorphic code. You’ll find out how to use protocols to constrain generics, which enables you to create generic functions with specific behavior. Along the way, this chapter introduces two essential protocols that often coincide with generics: Equatable and Comparable.

Listing 7.5. The generic function in action
let (firstString, lastString) = firstLast(array: ["pineapple", "cherry",
     "steam locomotive"])
print(firstString) // "pineapple"
print(lastString) // "steam locomotive"

Starting with a nongeneric function and later replacing all types with a generic is easier than starting to write a generic function from the get-go. But if you’re feeling confident, go ahead and write a generic function right away!

7.1.2. Reasoning about generics

Reasoning about generics can be hard and abstract. Sometimes a T is a String, and at a different time it’s an Int, and so forth. You can wrap both an integer and a string inside an array via the use of a generic function as shown here.