How do I delegate a call to [0..<n] in swift?

后端 未结 1 1681
梦谈多话
梦谈多话 2021-01-03 08:22

Background

For convenience, I used this alias:

typealias Deck = [Int]

My needs are expanding so I have now convert

相关标签:
1条回答
  • 2021-01-03 08:48

    For deck[0..<5] you need to implement the Sliceable protocol, which in turn requires CollectionType and SequenceType.

    The following example implements MutableCollectionType so that setting elements is forwarded to the array as well:

    class Deck
    {
        typealias DeckValueType = Int
        typealias DeckIndexType = Array<DeckValueType>.Index
    
        var deck : [DeckValueType] = [0, 1, 2, 3, 4, 5, 6] // just for demonstration ...
    }
    
    extension Deck : SequenceType {
        func generate() -> IndexingGenerator<[DeckValueType]> {
            return deck.generate()
        }
    }
    
    extension Deck: MutableCollectionType {
        var startIndex : DeckIndexType { return deck.startIndex }
        var endIndex : DeckIndexType { return deck.endIndex }
    
        subscript(index: DeckIndexType) -> DeckValueType {
            get {
                return deck[index]
            }
            set(newValue) {
                deck[index] = newValue
            }
        }
    }
    
    extension Deck : Sliceable {
        subscript (bounds: Range<DeckIndexType>) -> ArraySlice<DeckValueType> {
            get {
                return deck[bounds]
            }
        }
    }
    

    And then it works:

    let deck = Deck()
    for i in deck[0..<5] {
        println(i)
    }   
    

    The type aliases are not strictly necessary, but they make it easier to distinguish whether Int is used as the type of an array element or as the type for an array index.

    Also you can put all the code into the class definition. I have chosen separate extensions to make clear which method is needed for which protocol.

    0 讨论(0)
提交回复
热议问题