Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument for generic parameter 'T' could not be inferred

Tags:

generics

swift

I would like to create a generic helper function that does some processing. One of its inputs will be a function returning an array of something.

I can't figure out how to do this. I keep getting a compile error. I found the post

argument for generic parameter could not be inferred

and tried adding ...as [String] or ... as [Int], etc. but no luck.

func helperThatDoesSomeGenericProcessing<T>(displayedStrings: () -> [T])  -> [String]! {
    let listOfSomething: [T] = displayedStrings()
    // do something with listOfSomething
    return ["some", "resulting", "string", "from", "the", "input"]
}

func concreteFunction1() -> [AnyObject]! {
    var s: [String] = helperThatDoesSomeGenericProcessing {  // ERROR: Argument for generic parameter 'T' could not be inferred.
        var str = ["One", "Two", "Three"]
    } // tried 'as [String]' here

    // do something with s
    return s
}

func concreteFunction2() -> [AnyObject]! {
    var s: [Int] = helperThatDoesSomeGenericProcessing {  // ERROR: Argument for generic parameter 'T' could not be inferred.
        var i = [1, 2, 3]
    } // tried 'as [Int]' here

    // do something with s
    return s
}
like image 650
Daniel Avatar asked Jul 05 '15 11:07

Daniel


Video Answer


1 Answers

Adding return appropriately and explicitly declaring the concrete type of () -> [T] solve the errors ... but I'm not sure it will get you what you want. Anyway here's the code:

func helperThatDoesSomeGenericProcessing<T>(displayedStrings: () -> [T])  -> [String]! {
    let listOfSomething: [T] = displayedStrings()
    // do something with listOfSomething
    return ["some", "resulting", "string", "from", "the", "input"]
}

func concreteFunction1() -> [AnyObject]! {
    var s: [String]! = helperThatDoesSomeGenericProcessing {
        () -> [String] in // Explicit declared type
        var str = ["One", "Two", "Three"]
        return str
    } // tried 'as [String]' here

    // do something with s
    return s
}

func concreteFunction2() -> [AnyObject]! {
    var s: [String]! = helperThatDoesSomeGenericProcessing {
        () -> [Int] in // Explicit declared type
        var i = [1, 2, 3]
        return i
    } // tried 'as [Int]' here

    // do something with s
    return s
}

Notice I also corrected the type of var s since your generic function always returns an implicitly unwrapped optional array of strings [String]!. The return type is not generalised (i.e.: T or [T] etc.).

Probably you might need to change some type declarations in order to achieve your design needs.

Hope this helps

like image 66
Matteo Piombo Avatar answered Oct 13 '22 00:10

Matteo Piombo