There are some codes below, some gives compile time error some doesn't. Is there a bug or do I miss something about generics here?
1) Doesn't work:
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]
}
}
But this works:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T where T: DataType>(dataObjects: [T]) {
self.dataObjects = []
for dataObject in dataObjects {
self.dataObjects.append(dataObject)
}
}
}
2) Doesn't work:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = dataObjects //Cannot assign value of type [T] to type [DataType]
}
}
But this works:
class DataSource: NSObject {
var dataObjects: [DataType]
init<T:DataType>(dataObjects: [T]) {
self.dataObjects = []
for dataObject in dataObjects {
self.dataObjects.append(dataObject)
}
}
}
3) This also works:
class DataSource<T: DataType>: NSObject {
var dataObjects: [T]
init(dataObjects: [T]) {
self.dataObjects = dataObjects
}
}
Also what is the difference between T where T: DataType and T:DataType
P.S.:DataType is an empty protocol
init(dataObjects: [DataType])? It will still accept an array of anything that conforms to DataType right?