这是我在使用通用函数时遇到的一个小问题。由于缺乏泛型实践,可能是一个基本错误。无论如何,下面是与问题相关的代码。
通用函数本身,没有显示任何错误:
func setThingRevision<GenericType:Revisionable>(entity name: String) -> [(GenericType,Int)] {
var resultArray = [(GenericType,Int)]()
// ..... we do some useful magic ......
return resultArray
}
一些使用上述泛型函数的代码:
func setMyRealStuffRevision(entity name: String) -> [(RealType,Int)] {
return setThingRevision(entity: name)
}
这里是编译器在最后一个函数(setMyRealStuffRevision)中给出的错误信息:
Cannot convert return expression of type '[(_, Int)]' to return type '[(RealType, Int)]'
与其对消息感到惊讶,我想知道使用什么是正确的语法。
我的 RealType 与 GenericType 兼容,但我不确定是否需要向 setThingRevision 泛型函数提供一些信息,或者是否可以从上下文中推断出来。
--- 添加---
这是我为测试目的创建的假setThingRevision。
func setThingRevision<GenericType:Revisionable>(entity name: String) -> [(GenericType,Int)] {
var resultArray = [(GenericType,Int)]()
// Here name contains the name of a Core Data entity and getArrayFromEntity is
// a local function, extracting an array from the contents of the entity.
for item in getArrayFromEntity(name) as! [GenericType] {
resultArray.append((item, 99))
return resultArray
}
return resultArray
}
最佳答案
在类型安全语言中,如果无法完成“诱导”转换,编译器会告诉您该消息。不知何故 'var resultArray = (GenericType,Int)' 它没有被解释为可以转换为返回函数类型的类型。仔细检查编译器指定的 resultArray 类型。正确使用的语法不是使用“var”来创建 resultArray 变量,而是显式定义类型。
关于ios - 通用函数 -> 无法将返回表达式转换为返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603130/