In Swift, you can design generic functions and types by using generic parameters and constraints. This allows you to write flexible and reusable code while ensuring that the types used conform to certain requirements.
Here's an example of a generic function that calculates the maximum value from an array of elements that conform to the Comparable protocol:
func findMax(from array: [T]) -> T? {
guard !array.isEmpty else { return nil }
var currentMax = array[0]
for element in array {
if element > currentMax {
currentMax = element
}
}
return currentMax
}
// Usage
let numbers = [3, 5, 2, 8, 1]
if let maxNumber = findMax(from: numbers) {
print("Maximum number is \(maxNumber)")
}
In this function, T
is a generic type that must conform to the Comparable
protocol. This way, we ensure that the elements in the array can be compared to determine the maximum value.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?