我想创建一个执行某些处理的通用辅助函数。其中一个输入将是一个返回一组数据的函数。
我无法弄清楚如何做到这一点。我一直收到编译错误。我找到了帖子
argument for generic parameter could not be inferred
并尝试添加...as [String]
或... as [Int]
等,但没有运气。
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
}
答案 0 :(得分:5)
正确地添加return
并明确声明() -> [T]
的具体类型可以解决错误......但我不确定它能为您提供所需内容。无论如何,这里是代码:
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
}
注意我还更正了var s
的类型,因为你的泛型函数总是返回一个隐式解包的可选字符串数组[String]!
。返回类型不是一般化的(即:T
或[T]
等)。
可能您可能需要更改某些类型声明以满足您的设计需求。
希望这有帮助
答案 1 :(得分:0)
你的封闭体不会返回
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
}