> Anyway, it would not be correct to ".enumerate()" returns (Index, Element) 
> instead of (n, Element)?
> 
> I believe that the current behavior was thought when Slices had indices 
> starting with zero.
> 

The behavior of enumerate is easiest to explain when you give everything a name 
and lay them all out on the table: In particular, there is a difference between 
a Counter, an Index, a Key, a Value, and an Element.

Enumerate always works in terms of adding a counter, not an index. It was 
perhaps better served as a global method, since one cannot really improve its 
default implementation.

The rest are as follows:

╔════════════╦═════════════════╦═══════════════╦═════════════════╦════════════════════╗
║ Type       ║ Index*          ║ Key           ║ Value           ║ Element**    
      ║
╠════════════╬═════════════════╬═══════════════╬═════════════════╬════════════════════╣
║ Array      ║ 0-based offset  ║ N/A           ║ N/A             ║ Generic "T"  
      ║
╠════════════╬═════════════════╬═══════════════╬═════════════════╬════════════════════╣
║ ArraySlice ║ non-zero offset ║ N/A           ║ N/A             ║ Generic "T"  
      ║
╠════════════╬═════════════════╬═══════════════╬═════════════════╬════════════════════╣
║ Dictionary ║ DictionaryIndex ║ Generic "Key" ║ Generic "Value" ║ Tuple (Key, 
Value) ║
╚════════════╩═════════════════╩═══════════════╩═════════════════╩════════════════════╝

* Index is declared on CollectionType
** Element is declared on GeneratorType and referenced by SequenceType

That Array [T] does not behave like a Dictionary [Int:T] is possibly a sign 
that an AssociativeCollectionType is needed, something like:

protocol AssociativeCollectionType : CollectionType {
    typealias Key
    typealias Value
    typealias Element = (Key, Value)
    typealias KeySequenceType = AnySequence<Key>
    typealias ValueSequenceType = AnySequence<Value>
    
    var keys: KeySequenceType { get }
    var values: ValueSequenceType { get }
    subscript (key: Key) -> Value? { get set }
    func indexForKey(key:Key) -> Index

    mutating func removeValueForKey(key: Key) -> Value?
    mutating func updateValue(value: Value, forKey key: Key) -> Value?
}

Dictionary would support such a protocol directly. Array and ArraySlice (or 
even every CollectionType) might have a mapping function (lets bike shed 
“associative()” for now) to return an implementation of the interface, mapping:

- AssociativeCollectionType.Index = old Index
- AssociativeCollectionType.Key = old Index
- AssociativeCollectionType.Value = old Element
- AssociativeCollectionType.Element = old (Index, Element)

So maybe:

for (index, element) in someArray.associative() { … }

would do what the original idea requested: provide a (Index, Element) sequence 
for CollectionTypes.

-DW

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to