Generic in Swift

In the Swift programming language, the term “generic” refers to a type or function that can work with any type, rather than being tied to a specific type. This allows for greater flexibility and code reuse. For example, a generic function can be written to sort an array of any type, rather than having to write a separate sorting function for each type of array. Using generics can make your code more concise and easy to read, and can help you avoid code duplication.

Here is an example of a generic function in Swift that sorts an array of elements:

func sortArray<T: Comparable>(array: [T]) -> [T] {
    let sortedArray = array.sorted()
    return sortedArray
}

In this example, the sortArray function is a generic function that can sort an array of any type that conforms to the Comparable protocol. This means that the function can sort arrays of integers, strings, or any other type that can be compared using the < and > operators.

Here is how you could use this function to sort an array of integers:

let numbers = [10, -1, 3, 9, 2]
let sortedNumbers = sortArray(array: numbers)

The sortedNumbers constant would be equal to [-1, 2, 3, 9, 10] after this code is executed.

Spread the love

Leave a comment