It was very difficult for me to find a “working documentation” for using Sequence / IteratorProtocol in Swift 3. Several tutorials / articles seem to be for older Swift.
Imagine a game with a doubly linked list class DLList
...
public class Node {
I believe the following is a simple (?), Correct way to do this in one word, using the DLList
in the for
structure.
Step 1, DLList compatible with DLList: Sequence
public class DLList:Sequence {
It would seem that all you need to do is add a call to makeIterator
.
Step 2, write your iterator, matches IteratorProtocol
Since the class is DLList, we will call it DLListIterator. It would seem that,
1, you should have "init", which basically takes the group class in question
2, you should have a next
call, which should return one of the “things” that are magically related to your group class.
public class DLListIterator:IteratorProtocol { var dll:DLList
This works great. those. now you can go
var d:DLList = DLList() for n in d { print or whatever n }
you can use e = d.filter( {d.item blah} )
, etc. - well.
The question is a lot of talk about related types . In part 1, do you explicitly specify / add a "related type" somehow? Even if he did not explicitly demand , how would you do it explicitly? What the hell is a related type business?
The question is, in the second part, I am completely puzzled by how he "knows" that Node is a "thing" related to a DLList. Is there a way to make this explicit, or what I don't understand?
Quickness In addition, all this does not look very Swifty. It seems incredible to do everything just to add an iterator output. Is there a faster way for a real class in Swift3? (Not such a stupid example as "countdown numbers.")
The final question . I am pleased to note that the above also allows .filter. Actually, my example is “complete” - can I now do everything “iterator-wise” with a DLList, which can be done normally in Swift - maybe I “forgot some functions” or? Does DLList need to do a really good iterator yet?