I’m trying to make an extension for Array that will format it. The issue is that since I’m using generics, I need to define the type on the calling Array.
public struct ASValue<T: Hashable>: Hashable {
private let id = UUID()
var item: T
}
public extension Array {
func asCast<T: Hashable>() -> [ASValue<T>]{
self.map({
ASValue(item: $0 as! T)
})
}
}
// How can I call this without having to define the generic type?
@State private var numbers = [32, 78, 38, 28, 38].asCast() // Generic parameter 'T' could not be inferred
>Solution :
You actually don’t need a generic for this, just constraint the extension to only work with arrays of Hashable:
extension Array where Element: Hashable {
func asCast() -> [ASValue<Element>]{
self.map({
ASValue(item: $0)
})
}
}