Search code examples
swiftgenericstype-erasure

Is there any way to type erase only the parameter of closure in Swift?


Here's my code:

init<T: RandomAccessCollection>(
        items: T,
        build: @escaping (T.Element) -> any View
    ) where T.Element : Hashable {
        self.items = AnyRandomAccessCollection(items.map({ AnyHashable($0) }))
        self.itemBuild = // erase T.Element to AnyHashable to obtain a closure of type (AnyHashable) -> any View
    }

private let itemBuild: (AnyHashable) -> any View

I want to assign the build closure in the init to the itemBuild parameter, for that I need to somehow type erase T.Element which is Hashable into AnyHashable.

New to type erasing. Haven't really tried much that's worth mentioning.


Solution

  • I've figured it out. Here's how I did if anyone ever wonders the same thing:

    init<T: RandomAccessCollection>(
            items: T,
            build: @escaping (T.Element) -> any View
        ) where T.Element : Hashable {
            self.items = AnyRandomAccessCollection(items.map({ AnyHashable($0) }))
            let erasedType: (any Hashable) -> any View = { item in
                build(item as! T.Element)
            }
            self.itemBuild = erasedType
        }