I have a pretty good understanding of OO and Swift programming, but one area that really leaves me stuck is Generators and Sequences (I'm fine with the concept of protocols by the way).
For example, I performed this exercise from the Swift guide (Apple)
"EXPERIMENT Modify the anyCommonElements function to create a function that returns an array of elements that have two different sequences.
Inclusion of this:
func​ ​anyCommonElements​ <​T​, ​U​ ​where​ ​T​: ​SequenceType​, ​U​: ​SequenceType​, ​T​.​Generator​.​Element​: ​Equatable​, ​T​.​Generator​.​Element​ == ​U​.​Generator​.​Element​> (​lhs​: ​T​, ​rhs​: ​U​) -> ​Bool​ { for​ ​lhsItem​ ​in​ ​lhs​ { for​ ​rhsItem​ ​in​ ​rhs​ { if​ ​lhsItem​ == ​rhsItem​ { return​ ​true } } } return​ ​false }
In it:
func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> [T.Generator.Element]? { var commonElements:[T.Generator.Element]? = nil for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { if (commonElements == nil) { commonElements = [] //init the array if not already } commonElements?.append(lhsItem) //add matching item to the array } } } return commonElements? //return nil or array of matched elements }
I am pleased with the solution I wrote and it works well, including an optional return, however I am lost as to why the return type of the commonElements array should be this :
var commonElements:[T.Generator.Element]
Instead of this:
var commonElements:[T]
I read a fair cue ball on this issue, including:
https://schani.wordpress.com/2014/06/06/generators-in-swift/
http://robots.thoughtbot.com/swift-sequences
http://natashatherobot.com/swift-conform-to-sequence-protocol/
But I'm still completely lost - can someone please explain this in simple language or just a little abstract and not easy to describe?
It would be very nice, thanks, John