In Swift, we can use generics to create a wrapper that can contain any type of value. This can be useful when we want to store and pass around values without having to worry about their specific type.
One way to create a generic wrapper in Swift is by using a protocol and type erasure. Here's an example:
main.swift643 chars26 lines
In this example, we define a protocol AnyWrapper
that has an associated type WrappedType
and a read-only property wrappedValue
of that type.
Next, we define a type-erased wrapper Wrapper<T>
that conforms to AnyWrapper
. This wrapper contains a private closure _wrappedValue
that returns the wrapped value, and it initializes itself with any object that conforms to AnyWrapper
and has the same associated type as T
.
Finally, we use the Wrapper
type to create generic wrappers for strings and integers, and we print out their values to verify that the type erasure works as expected.
gistlibby LogSnag