我试图将加载/保存功能添加到通用缓存类中,如下所示:
class Cache<T:Hashable, U:AnyObject> {
private var cache: [T:U] = [:]
private var url: NSURL!
func load() {
if let path = self.url where NSFileManager().isReadableFileAtPath(path.path!) {
if let dict = NSDictionary(contentsOfURL: path) {
// The next line is rejected by the compiler as always failing the cast
cache = (dict as? DictType)!
}
}
}
func save() {
if let path = self.url where NSFileManager().isWritableFileAtPath(path.path!) {
// The next line is rejected by the compiler as the method not existing
let result = cache.writeToURL(path, atomically: false)
}
}
.
.
.
}
如果我使用具体类型,这是有效的,但转换为泛型显然会带走足够的信息,编译器不再愿意接受它。 有办法吗?
我也试过循环遍历NSDictionary,但是例如加载例程中的循环然后抱怨它没有键的类型(并且不接受从allKeys返回的内容) );我也不能强迫/胁迫T型。