Argument for general parameter "T" cannot be displayed

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

I can’t figure out how to do this. I keep getting a compilation error. I found a message

argument for general parameter cannot be inferred

and tried to add ...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 } 
+6
source share
2 answers

By adding return appropriately and explicitly declaring a specific type () -> [T] , we resolve the errors ... but I'm not sure if it will give you what you want. Anyway, here is 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 } 

Note that I also adjusted the var s type, since your common function always returns an implicitly expanded optional array of strings [String]! . The return type is not generalized (ie: T or [T] , etc.).

You may probably need to modify some type declarations to meet your design needs.

Hope this helps

+5
source

Hi, your body closure is not coming back

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

All Articles