Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between SequenceType and CollectionType in swift?

Tags:

swift

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?

like image 757
Ankit Goel Avatar asked Jun 01 '15 04:06

Ankit Goel


People also ask

What's the main difference between the array set and dictionary collection type?

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.

Which of these collections use a key pair value in Swift?

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.


1 Answers

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

like image 184
Vivek Molkar Avatar answered Sep 19 '22 15:09

Vivek Molkar