Please explain the difference between SequenceType
, GeneratorType
and CollectionType
in the Swift programming language.
Also, if I am implementing my own data structure what would be the advantage of using SequenceType
, GeneratorType
or CollectionType
protocols?
Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
In swift dictionaries are used to store values with key-value pair association in an unordered manner. In dictionaries, we can store the same type of keys and the same type of values with no defined order.
GeneratorType (IteratorProtocol in Swift 3): Generators
is something that can give the next
element of some sequence, if there is no element it returns nil
. Generators
encapsulates iteration state and interfaces for iteration over a sequence.
A generator works by providing a single method, namely – next()
, which simply returns the next value from the underlying sequence
.
Following classes Adopt GeneratorType Protocol:
DictionaryGenerator, EmptyGenerator, more here.
SequenceType (Sequence in Swift 3): A Sequence
represent a series of values. Sequence
is a type that can be iterated with a for...in
loop.
Essentially a sequence is a generator factory; something that knows how to make generators for a sequence.
Following classes Adopt SequenceType Protocol:
NSArray, NSDictionary, NSSet and more.
CollectionType (Collection in Swift 3): Collection
is a SequenceType
that can be accessed via subscript and defines a startIndex
and endIndex
. Collection
is a step beyond a sequence; individual elements of a collection can be accessed multiple times.
CollectionType
inherits from SequenceType
Following classes Adopt CollectionType Protocol:
Array, Dictionary, Set, Range and more.
Form more information you can see this, this, and this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With