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.swift63 chars4 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.swift112 chars3 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.swift95 chars4 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.swift363 chars19 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