【发布时间】:2019-02-09 04:17:06
【问题描述】:
这是我在使用通用函数时遇到的一个小问题。由于缺乏泛型实践,可能是一个基本错误。无论如何,下面是与问题相关的代码。
泛型函数本身,没有显示任何错误:
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
}
【问题讨论】:
-
您能否编辑您的问题以提供一个证明错误的minimal reproducible example。
-
让我看看我能不能做点什么。我已经可以说的是 RealType 是 NSManagedObject 的子类。
-
我不太明白发生了什么,因为对我来说(即使 RealType 是从 NSManagedObject 继承的)这段代码是可构建的。
-
@Paulw11。我编辑了帖子(见后---添加---)希望这个添加的代码能让你简单地测试。在我的情况下,我仍然得到与此测试代码相同的错误。
-
它仍然不是minimal reproducible example - 因为它不完整。请尝试提供完整代码,而不是简单地粘贴到 Xcode 中会产生错误。例如
revisionKanaArray是什么?应该是resultArray?
标签: ios swift generic-programming