下面有一些代码,有些代码会给出编译时错误。有没有错误,或者我在这里想念一些关于泛型的东西?
1)不起作用:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T where T: DataType>(dataObjects: [T]) {
self.dataObjects = dataObjects //Cannot assign value of type [T] to type [DataType]
}
}
但这有效:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T where T: DataType>(dataObjects: [T]) {
self.dataObjects = []
for dataObject in dataObjects {
self.dataObjects.append(dataObject)
}
}
}
2)不起作用:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = dataObjects //Cannot assign value of type [T] to type [DataType]
}
}
但这有效:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = []
for dataObject in dataObjects {
self.dataObjects.append(dataObject)
}
}
}
第3) 这也有效:
class DataSource<T: DataType>: NSObject {
var dataObjects: [T]
init(dataObjects: [T]) {
self.dataObjects = dataObjects
}
}
T where T: DataType
和T:DataType
P.S.:DataType是一个空协议
答案 0 :(得分:2)
最有可能的问题是,您的协议不是从引用DataType继承,而是数组需要对象。
例如,Any
并不总是通过引用
protocol DataType: Any {
}
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = dataObjects //Cannot assign value of type [T] to type [DataType]
}
}
另一方面,AnyObject总是:
protocol DataType: AnyObject {
}
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = dataObjects //Works fine
}
}