考虑我的两个班级:
// Person.swift
class Person {
var parents: Parents?
// ...
}
// Parents.swift. Only a collection of parents with some helper methods.
class Parents {
var parents = [Person]()
// ...
}
如何使用Parents
的迭代器使parents
在for循环中进行迭代。这不是一个真实的应用程序。我只是好奇。只是想使用for parent in myParents
而不是for parent in myParents.parents
。
答案 0 :(得分:3)
执行此操作的方法是让您的Parents
类符合Sequence
Protocol,实施makeIterator
方法,然后通过调用makeIterator
传递结果包含的Array<Person>
// Person.swift
class Person {
var parents: Parents?
// ...
}
// Parents.swift. Only a collection of parents with some helper methods.
class Parents{
var parents = [Person]()
// ...
}
// conform to Sequence Protocol
extension Parents: Sequence {
func makeIterator() -> Array<Person>.Iterator {
return parents.makeIterator()
}
}
let myself = Person()
if let myParents = myself.parents {
for person in myParents {
}
}