Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic parameter 'T' could not be inferred on extension

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
        })
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading