我有一个实现协议BaseModels
的父类Sequence
:
class BaseModel {
var dict : Dictionary
init (json: AnyObject?) { dict = json as? Dictionary }
}
class BaseModels : Sequence {
var arr : Array<Dictionary>
init (json: AnyObject?) { arr = json as? Array<Dictionary> }
func makeIterator() -> AnyIterator<BaseModel> {
var nextIndex = 0;
return AnyIterator {
guard let arr = self.arr, nextIndex < arr.count else { return nil }
let curIndex = nextIndex; nextIndex += 1;
return BaseModel(json: arr[curIndex] as AnyObject?)
}
}
}
我有从这个父母继承的孩子班:
class Child : BaseModel { ... }
class Childs : BaseModels {
func makeIterator() -> AnyIterator<Child> {
var nextIndex = 0;
return AnyIterator {
guard let arr = self.arr, nextIndex < arr.count else { return nil }
let curIndex = nextIndex; nextIndex += 1;
return Child(json: arr[curIndex] as AnyObject?)
}
}
}
但是当我这样做时:
let childs = Childs(json: someJsonArray);
for (idx, el) in childs.enumerate() {
// when I check the el's data type in here, its type is actually BaseModel, not Child.
}
为什么el
类型是BaseModel,而不是Child?如何正确实现这一点,以便在调用enumerate
或for ... in ...
时,它返回Child类型而不是BaseModel类?
PS:当我在override
前面添加func makeIterator() -> AnyIterator<Child>
时,Xcode说&#34;方法不会覆盖其超类中的任何方法&#34;。