Sean Levin - The Wacky Wild World of Swift Collection Types

Sean Levin - The Wacky Wild World of Swift Collection Types

In Objective-C we have NSArrays.

In Swift we have Arrays, Generators, FlattenBidirectionCollection, LazySequenceType, ReverseRandomAccessIndex, and 62 other types directly related to solving all your fine grained ordered collection needs.

Why do all of these exist? How can we even begin to remember when to use which? What insane person could possibly need this many?

In this talk Sean will dive into some stories and theories, attempting to answer these very questions. We will be covering topics in generic programming, performance, and programming languages on down to the very fundamentals of numbers and math. You will come away with some juicy crowd pleasing knowledge you can take home to impress your friends, family, and coworkers.

Recording from the March 2016 Brooklyn Swift Developers Meetup: http://meetup.com/Brooklyn-Swift-Developers/events/229464421/

Video: https://vimeo.com/160350970

Transcript

  1. WACKY WILD WORLD OF SWIFT COLLECTION TYPES 1

  2. NSArray NSMutableArray NSPointerArray 2

  3. SWIFT 2.2 LIBRARY AnyBidirectionalCollection AnyBidirectionalIndex AnyForwardCollection AnyForwardIndex AnyGenerator AnyRandomAccessCollection AnyRandomAccessIndex

    AnySequence Array ArraySlice AutoreleasingUnsafeMutablePointer Bit Bool COpaquePointer CVaListPointer Character ClosedInterval CodeUnit CollectionOfOne ContiguousArray Dictionary DictionaryGenerator DictionaryIndex DictionaryLiteral Double EmptyCollection EmptyGenerator EnumerateGenerator EnumerateSequence FlattenBidirectionalCollection FlattenBidirectionalCollectionIndex FlattenCollection FlattenCollectionIndex FlattenGenerator FlattenSequence PermutationGenerator PlaygroundQuickLook Process Range RangeGenerator RawByte Repeat ReverseCollection ReverseIndex ReverseRandomAccessCollection ReverseRandomAccessIndex Set SetGenerator SetIndex Slice StaticString StrideThrough StrideThroughGenerator StrideTo StrideToGenerator String String.CharacterView String.CharacterView.Index String.UTF16View String.UTF16View.Index String.UTF8View String.UTF8View.Index String.UnicodeScalarView String.UnicodeScalarView.Generator String.UnicodeScalarView.Index String.UnicodeScalarView.UnicodeScalarIndex UInt UInt16 UInt32 UInt64 FloatLiteralConvertible FloatingPointType ForwardIndexType GeneratorType Hashable Indexable IntegerArithmeticType IntegerLiteralConvertible IntegerType IntervalType LazyCollectionType LazySequenceType MirrorPathType MutableCollectionType MutableIndexable MutableSliceable NilLiteralConvertible OptionSetType OutputStreamType RandomAccessIndexType RangeReplaceableCollectionType RawRepresentable ReverseIndexType SequenceType SetAlgebraType SignedIntegerType SignedNumberType Streamable Strideable StringInterpolationConvertible StringLiteralConvertible UnicodeCodecType UnicodeScalarLiteralConvertible UnsignedIntegerType Float Float80 FloatingPointClassification GeneratorOfOne GeneratorSequence HalfOpenInterval ImplicitlyUnwrappedOptional IndexingGenerator Int Int16 Int32 Int64 Int8 IntMax JoinGenerator JoinSequence LazyCollection LazyFilterCollection LazyFilterGenerator LazyFilterIndex LazyFilterSequence LazyMapCollection LazyMapGenerator LazyMapSequence LazySequence ManagedBuffer ManagedBufferPointer ManagedProtoBuffer Mirror Mirror.AncestorRepresentation Mirror.DisplayStyle MutableSlice NonObjectiveCBase ObjectIdentifier Optional UInt8 UTF16 UTF32 UTF8 UnicodeDecodingResult UnicodeScalar Unmanaged UnsafeBufferPointer UnsafeBufferPointerGenerator UnsafeMutableBufferPointer UnsafeMutablePointer UnsafePointer VaListBuilder Zip2Generator Zip2Sequence AbsoluteValuable AnyCollectionType AnyObject ArrayLiteralConvertible BidirectionalIndexType BitwiseOperationsType BooleanLiteralConvertible BooleanType CVarArgType CollectionType Comparable CustomDebugStringConvertible CustomLeafReflectable CustomPlaygroundQuickLookable CustomReflectable CustomStringConvertible DictionaryLiteralConvertible Equatable ErrorType ExtendedGraphemeClusterLiteralConvertible 3
  4. SWIFT 2.2 LIBRARY FloatLiteralConvertible FloatingPointType ForwardIndexType GeneratorType Hashable Indexable IntegerArithmeticType

    IntegerLiteralConvertible IntegerType IntervalType LazyCollectionType LazySequenceType MirrorPathType MutableCollectionType MutableIndexable MutableSliceable NilLiteralConvertible OptionSetType OutputStreamType RandomAccessIndexType RangeReplaceableCollectionType RawRepresentable ReverseIndexType SequenceType SetAlgebraType SignedIntegerType SignedNumberType Streamable Strideable StringInterpolationConvertible StringLiteralConvertible UnicodeCodecType UnicodeScalarLiteralConvertible UnsignedIntegerType UInt8 UTF16 UTF32 UTF8 UnicodeDecodingResult UnicodeScalar Unmanaged UnsafeBufferPointer UnsafeBufferPointerGenerator UnsafeMutableBufferPointer UnsafeMutablePointer UnsafePointer VaListBuilder Zip2Generator Zip2Sequence AbsoluteValuable AnyCollectionType AnyObject ArrayLiteralConvertible BidirectionalIndexType BitwiseOperationsType BooleanLiteralConvertible BooleanType CVarArgType CollectionType Comparable CustomDebugStringConvertible CustomLeafReflectable CustomPlaygroundQuickLookable CustomReflectable CustomStringConvertible DictionaryLiteralConvertible Equatable ErrorType ExtendedGraphemeClusterLiteralConvertible PermutationGenerator PlaygroundQuickLook Process Range RangeGenerator RawByte Repeat ReverseCollection ReverseIndex ReverseRandomAccessCollection ReverseRandomAccessIndex Set SetGenerator SetIndex Slice StaticString StrideThrough StrideThroughGenerator StrideTo StrideToGenerator String String.CharacterView String.CharacterView.Index String.UTF16View String.UTF16View.Index String.UTF8View String.UTF8View.Index String.UnicodeScalarView String.UnicodeScalarView.Generator String.UnicodeScalarView.Index String.UnicodeScalarView.UnicodeScalarIndex UInt UInt16 UInt32 UInt64 Float Float80 FloatingPointClassification GeneratorOfOne GeneratorSequence HalfOpenInterval ImplicitlyUnwrappedOptional IndexingGenerator Int Int16 Int32 Int64 Int8 IntMax JoinGenerator JoinSequence LazyCollection LazyFilterCollection LazyFilterGenerator LazyFilterIndex LazyFilterSequence LazyMapCollection LazyMapGenerator LazyMapSequence LazySequence ManagedBuffer ManagedBufferPointer ManagedProtoBuffer Mirror Mirror.AncestorRepresentation Mirror.DisplayStyle MutableSlice NonObjectiveCBase ObjectIdentifier Optional AnyBidirectionalCollection AnyBidirectionalIndex AnyForwardCollection AnyForwardIndex AnyGenerator AnyRandomAccessCollection AnyRandomAccessIndex AnySequence Array ArraySlice AutoreleasingUnsafeMutablePointer Bit Bool COpaquePointer CVaListPointer Character ClosedInterval CodeUnit CollectionOfOne ContiguousArray Dictionary DictionaryGenerator DictionaryIndex DictionaryLiteral Double EmptyCollection EmptyGenerator EnumerateGenerator EnumerateSequence FlattenBidirectionalCollection FlattenBidirectionalCollectionIndex FlattenCollection FlattenCollectionIndex FlattenGenerator FlattenSequence 4
  5. ORDERED COLLECTION TYPES AnyBidirectionalCollection AnyBidirectionalIndex AnyForwardCollection AnyForwardIndex AnyGenerator AnyRandomAccessCollection AnyRandomAccessIndex

    AnySequence Array ArraySlice CollectionOfOne ContiguousArray DictionaryGenerator DictionaryIndex EmptyCollection EmptyGenerator EnumerateGenerator EnumerateSequence FlattenBidirectionalCollection FlattenBidirectionalCollectionIndex FlattenCollection UnsafeBufferPointer UnsafeBufferPointerGenerator UnsafeMutableBufferPointer Zip2Generator Zip2Sequence AnyCollectionType BidirectionalIndexType CollectionType ForwardIndexType GeneratorType Indexable LazyCollectionType LazySequenceType MutableCollectionType MutableIndexable MutableSliceable RandomAccessIndexType RangeReplaceableCollectionType ReverseIndexType SequenceType FlattenCollectionIndex FlattenGenerator FlattenSequence GeneratorOfOne GeneratorSequence IndexingGenerator JoinGenerator JoinSequence LazyCollection LazyFilterCollection LazyFilterGenerator LazyFilterIndex LazyFilterSequence LazyMapCollection LazyMapGenerator LazyMapSequence LazySequence MutableSlice PermutationGenerator Range RangeGenerator ReverseCollection ReverseIndex ReverseRandomAccessCollection ReverseRandomAccessIndex SetGenerator SetIndex Slice StrideThrough StrideThroughGenerator StrideTo StrideToGenerator String.CharacterView String.CharacterView.Index String.UTF16View String.UTF16View.Index String.UTF8View String.UTF8View.Index String.UnicodeScalarView String.UnicodeScalarView.Generator String.UnicodeScalarView.Index String.UnicodeScalarView.UnicodeScalarIndex 5
  6. THESIS That's a lot of stuff 6

  7. THESIS That's a lot of abstract stuff 7

  8. THESIS That's a lot of abstract stuff especially when we

    have Array 8
  9. And you should use Array 9

  10. UNAVOIDABLE func elementsEqual<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence)

    -> Bool 10
  11. UNAVOIDABLE var lazy: LazyCollection<Array<Element>> { get } 11

  12. UNAVOIDABLE func flatMap<Intermediate : CollectionType>(transform: (Base.Generator.Elements.Generator.Element) -> Intermediate) -> LazyCollection<FlattenCollection<LazyMapCollection<Base.Generator.Elements,

    Intermediate>>> 12
  13. EXPECTATIONS > four key concepts > code (to keep it

    real) > a few fun features > Existential Types 13
  14. FOUR KEY CONCEPTS > Generator > Sequence > Index >

    Collection 14
  15. 1. GENERATOR Let's you step through a group of items

    one at a time protocol GeneratorType { associatedtype Element mutating func next() -> Self.Element? } 15
  16. 16

  17. 17

  18. 18

  19. 19

  20. 2. SEQUENCE for x in [1, 2, 3] { /*

    do stuff */ } for y in [1, 2, 3].enumerate() { /* do stuff */ } for z in "swiftz rules!".UTF8View { /* do stuff */ } for whatever in __________ { /* do stuff */ } 20
  21. 2. SEQUENCE protocol SequenceType { associatedtype Generator : GeneratorType func

    generate() -> Self.Generator } 21
  22. 22

  23. 23

  24. GOT THESE FOR FREE dropFirst, dropLast, forEach map, prefix, split,

    suffix, contains, lazy, elementsEqual, enumerate, filter, flatMap, lexicographicalCompare, maxElement, minElement, reduce, reverse, sort, startsWith, joinWithSeparator 24
  25. 25

  26. 26

  27. 3. INDEX Represents a discrete value in a series protocol

    ForwardIndexType : Equatable { func successor() -> Self } func ==(lhs: Self, rhs: Self) -> Bool 27
  28. 28

  29. 29

  30. 30

  31. 31

  32. 32

  33. 4. COLLECTION protocol CollectionType: SequenceType, Indexable protocol Indexable { associatedtype

    Index : ForwardIndexType var endIndex: Self.Index var startIndex : Self.Index subscript(position: Self.Index) -> Self._Element { get } } 33
  34. 4. COLLECTION Its what makes something look like an array.

    let todaysCar = armadaOfBentlys[76] 34
  35. 35

  36. 36

  37. 37

  38. 38

  39. 39

  40. 4. COLLECTION BidirectionalIndexType RandomAccessIndexType ReverseIndexType MutableCollectionType MutableIndexable RangeReplaceableCollectionType 40

  41. FOUR KEY CONCEPTS > Generator > Sequence > Index >

    Collection 41
  42. SWIFT 3.0 GeneratorType will become Iterator "Type" is disappearing Indexes

    combine with Collection 42
  43. SMART TYPES SMART FUN FlattenBidirectionalCollection FlattenBidirectionalCollectionIndex FlattenCollection FlattenCollectionIndex FlattenGenerator FlattenSequence

    43
  44. SMART TYPES SMART FUN LazyCollection LazyFilterCollection LazyFilterGenerator LazyFilterIndex LazyFilterSequence LazyMapCollection

    LazyMapGenerator LazyMapSequence LazySequence LazyCollectionType LazySequenceType 44
  45. SMART TYPES SMART FUN ArraySlice MutableSlice Slice MutableSliceable 45

  46. SMART TYPES SMART FUN CollectionOfOne GeneratorOfOne EmptyCollection EmptyGenerator 46

  47. EXISTENTIAL TYPES AnyBidirectionalCollection AnyBidirectionalIndex AnyForwardCollection AnyForwardIndex AnyGenerator AnyRandomAccessCollection AnyRandomAccessIndex AnySequence

    47
  48. EXISTENTIAL TYPES func doSomeStuffWithGenerator(g: GeneratorType) { /* do stuff */

    } error: protocol 'GeneratorType' can only be used as a generic constraint because it has Self or associated type requirements protocol GeneratorType { associatedtype Element mutating func next() -> Self.Element? } 48
  49. EXISTENTIAL TYPES struct AnyGenerator2<T> : GeneratorType { typealias Element =

    T var localNext : () -> T? init<Base: GeneratorType where Base.Element == T>(var _ g: Base) { self.localNext = { () -> T? in return g.next() } } mutating func next() -> T? { return self.localNext() } } 49
  50. TYPES COMPOSE FUNNY func flatMap<Intermediate : CollectionType> (transform: (Base.Generator.Elements.Generator.Element) ->

    Intermediate) -> LazyCollection<FlattenCollection <LazyMapCollection<Base.Generator.Elements, Intermediate>>> 50
  51. EXISTENTIAL TYPES AnyBidirectionalCollection AnyBidirectionalIndex AnyForwardCollection AnyForwardIndex AnyGenerator AnyRandomAccessCollection AnyRandomAccessIndex AnySequence

    51
  52. THESIS That's a lot of abstract stuff especially when we

    have Array It's there when you need it. 52
  53. ELEMENTS OF PROGRAMMING ALEXANDER STEPANOV AND PAUL MCJONES 53

  54. HOMEWORK 1. Make a LinkedList type 2. Make it conform

    to CollectionType 54
  55. Sean Levin Yahoo @seanlevin 55