Home > Software engineering >  Generic parameter 'T' could not be inferred on extension
Generic parameter 'T' could not be inferred on extension

Time:08-24

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

CodePudding user response:

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)
        })
    }
}

CodePudding user response:

I like the other posted solution (i.e. use of where Element...). But technically to resolve the error all you need to do is to give the compiler a clue on what type of output you expect:

@State private var numbers: [ASValue<Int>] = [32, 78, 38, 28, 38].asCast()
  • Related