ios - 通用函数 -> 无法将返回表达式转换为返回类型

标签 ios swift generic-programming

这是我在使用通用函数时遇到的一个小问题。由于缺乏泛型实践,可能是一个基本错误。无论如何,下面是与问题相关的代码。

通用函数本身,没有显示任何错误:

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)]'

与其对消息感到惊讶,我想知道使用什么是正确的语法。

我的 RealTypeGenericType 兼容,但我不确定是否需要向 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/

相关文章:

iphone - 如何创建从屏幕顶部推送的 UINavigationController?

ios - SQLite "database disk image is malformed"

swift - 使用 Unresolved Identifier 添加第二个 pin MapKit swift

ios - 启动屏幕不能设置自定义类名

c++ - 类 <template-parameter-1-2> 的默认参数的重新定义

Java 泛型 - 从 "capture#1 of ?"到 "A"的未经检查的强制转换

ios - 当我在应用程序 didFinishLaunchingWithOptions 中收到 UIApplicationLaunchOptionsLocationKey 时,是否初始化 viewController?

ios - FBSDKGraphRequest 如何获取个人资料封面照片?

c++ - 有没有一种通用的方法来传递需要较少工作的重载方法的指针(比我的示例)

objective-c - iOS Blocks - 定义类似 UIView 动画的 block