4

下面有一些代码,有些给出编译时错误,有些则没有。这里有错误还是我错过了一些关于泛型的东西?

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

PS:DataType 是一个空协议

4

1 回答 1

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
    }
}
于 2016-04-19T13:35:43.833 回答