jun*_*cia 4 arrays collections iterator sequence swift
考虑我的两个类:
// Person.swift
class Person {
var parents: Parents?
// ...
}
// Parents.swift. Only a collection of parents with some helper methods.
class Parents {
var parents = [Person]()
// ...
}
Run Code Online (Sandbox Code Playgroud)
如何Parents使用parents. 这不是一个真实世界的应用程序。我只是好奇。只是想使用for parent in myParents而不是for parent in myParents.parents.
小智 5
这样做的方法是让您的Parents类符合SequenceProtocol,实现一个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 {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1961 次 |
| 最近记录: |