Cannot Assign Protocol Array to Shared Array

Below are some codes, some of which give a compile-time error. Is there a mistake or am I missing 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 it 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 it 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
    }
}

What is the difference between T where T: DataTypeandT:DataType

PS: DataType - empty protocol

+4
source share
1 answer

Most likely, the problem is that your protocol does not inherit from the DataType reference type, while the array expects objects.

For example, Anynot always by reference

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, on the other hand, is always:

protocol DataType: AnyObject {
}

class DataSource: NSObject {
    var dataObjects: [DataType]

    init<T:DataType>(dataObjects: [T]) {
        self.dataObjects = dataObjects //Works fine
    }
}
+2

All Articles