在一般实现中无法将[Int]转换为[Int] [英] Cannot convert [Int] to [Int] in generic implementation

查看:114
本文介绍了在一般实现中无法将[Int]转换为[Int]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图创建通用数据源时遇到了这个错误,我想知道为什么它不能编译.

Trying to create a generic data source I bumped into this error and I was wondering why this isn't compilable.

错误:

无法将类型为[[Int]"的返回表达式转换为类型为[[Int]"

代码:

protocol DataSource {
    func getData<T> () -> [T]
}

class IntDataSource<Int>: DataSource {
    let data:[Int] = []
    func getData<Int>() -> [Int] {
        return data
    }
}

在IntDataSource中的return语句上引发了错误.

The error is thrown on the return statement in IntDataSource.

我知道可以使用

typealias DataType
var data: DataType? { get }

但是我主要对为什么编译器不想接受return语句感兴趣.有什么想法吗?

But I'm mainly interested in why the compiler doesn't want to accept the return statement. Any ideas?

部分问题还在于,如果先前的代码不可编译,那么为什么随后的公平竞争?

Part of the question is also why if the previous code is not compilable is the following fair game?

class IntDataSource<Int>: DataSource {
    func getData<Int>() -> [Int] {
        let data:[Int] = []
        return data
    }
}

此版本也可以毫无问题地编译

This version also compiles without issues

class IntDataSource<Int>: DataSource {

    func getData<Int>() -> [Int] {
        return getIntData()
    }

    func getIntData<Int>() -> [Int] {
        let data:[Int] = []
        return data
    }
}

推荐答案

奇怪的"编译器错误

Cannot convert return expression of type '[Int]' to return type '[Int]'

可以解释如下:

您的类定义中的<Int><Int> 在方法定义中引入一个新的泛型 类型占位符称为Int(因此,外部<Int>隐藏具有相同名称的全局类型,内部<Int>隐藏 外层).您的课程定义等同于

Both the <Int> in your class definition and the <Int> in the method definition introduce a new generic type placeholder called Int (and therefore the outer <Int> hides the global type with the same name, and the inner <Int> hides the outer one). Your class definition is equivalent to

class IntDataSource<A>: DataSource {
    let data:[A] = []
    func getData<B>() -> [B] {
        return data 
    }
}

现在编译器错误是可以理解的:

And now the compiler error is understandable:

cannot convert return expression of type '[A]' to return type '[B]'

这篇关于在一般实现中无法将[Int]转换为[Int]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆