数组 – 无法将协议数组分配给通用数组

下面有一些代码,有些代码会给出编译时错误.有错误还是我想念一些关于仿制药的东西?

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还有什么区别T:DataType和T:DataType

P.S.:DataType是一个空协议

最佳答案 最有可能的问题是,您的协议不是从引用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
    }
}
点赞