Swift
Beginner
1 min read
inout Parameters and Generic Functions
Example
// inout parameters
func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 10, y = 20
swap(&x, &y)
print(x, y) // 20 10
// Generic function with constraint
func findFirst<T: Equatable>(_ item: T, in array: [T]) -> Int? {
for (index, element) in array.enumerated() {
if element == item { return index }
}
return nil
}
findFirst("banana", in: ["apple", "banana", "cherry"]) // Optional(1)
// Multiple constraints
func showMax<T: Comparable & CustomStringConvertible>(_ a: T, _ b: T) -> String {
let max = a > b ? a : b
return "Max: \(max.description)"
}
// Where clause on generic
func allUnique<T: Hashable>(_ array: [T]) -> Bool {
Set(array).count == array.count
}
allUnique([1, 2, 3, 4]) // true
allUnique([1, 2, 2, 4]) // false
// Generic type with associated type protocol
protocol Stack {
associatedtype Element
mutating func push(_ item: Element)
mutating func pop() -> Element?
var top: Element? { get }
}