genericsi in swift

Generics in Swift allow you to write reusable code that can work with any type. To define a generic function, you need to use type parameters. These are placeholders for actual types that you will use when you call the function.

Here is a simple example of a generic function that takes two integers and returns the sum:

main.swift
func sum<T: Numeric>(_ a: T, _ b: T) -> T {
    return a + b
}
63 chars
4 lines

In this example, we have defined a type parameter T that conforms to the Numeric protocol. This means that T can be any type that provides basic arithmetic operations like addition, subtraction, multiplication, and division.

To use this function, you simply specify the actual types for the type parameter:

main.swift
let intSum = sum(5, 10) // intSum is of type Int
let doubleSum = sum(3.14, 1.59) // doubleSum is of type Double
112 chars
3 lines

You can also use type constraints to restrict the types that can be used with a generic function. For example, if you want to make sure that the type parameter implements a specific protocol, you can add a type constraint like this:

main.swift
func printDescription<T: CustomStringConvertible>(_ value: T) {
    print(value.description)
}
95 chars
4 lines

In this example, we have added a type constraint that specifies the T must conform to the CustomStringConvertible protocol. This means that the description property is guaranteed to exist, so we can safely print it.

Swift also supports associated types, which allow you to define a protocol with a placeholder for a type that will be provided by a conforming type. Here is an example:

main.swift
protocol Stack {
    associatedtype Element
    mutating func push(_ element: Element)
    mutating func pop() -> Element?
}

struct IntStack: Stack {
    typealias Element = Int
    var items = [Int]()
    
    mutating func push(_ element: Int) {
        items.append(element)
    }
    
    mutating func pop() -> Int? {
        return items.popLast()
    }
}
363 chars
19 lines

In this example, we have defined a protocol Stack that has an associated type Element. This means that any conforming type must provide a concrete type for Element. We have then created a struct IntStack that conforms to Stack and provides Int as the concrete type for Element. This allows us to create an instance of IntStack and add or remove integers from it.

Generics and associated types are powerful features in Swift that allow you to write flexible and reusable code. By using type parameters, type constraints, and associated types, you can create functions and protocols that work with any type that meets your requirements.

gistlibby LogSnag