create a generic wrapper in swift

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.swift
// Define a protocol for our wrapper
protocol AnyWrapper {
    associatedtype WrappedType
    var wrappedValue: WrappedType { get }
}

// Define a type-erased wrapper that conforms to our protocol
struct Wrapper<T>: AnyWrapper {
    private let _wrappedValue: () -> T

    init<U: AnyWrapper>(_ wrapper: U) where U.WrappedType == T {
        self._wrappedValue = { wrapper.wrappedValue }
    }

    var wrappedValue: T {
        return _wrappedValue()
    }
}

// Example usage
let stringWrapper = Wrapper("Hello, world!")
let intWrapper = Wrapper(42)

print(stringWrapper.wrappedValue) // "Hello, world!"
print(intWrapper.wrappedValue) // 42
643 chars
26 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