How to send a call to [0 .. <n] in swift?

Background

For convenience, I used this alias:

typealias Deck = [Int]

My needs are expanding, so I have now converted my code to:

class Deck
{
  var deck : [Int]
  // ... other members
}

I can delegate most of my calls before self.deck, but after several search attempts, I still have problems with how to delegate this call:

let deck = Deck()
for i in deck[0..<5] { }   // <--- PROBLEMS HERE

Question

How to implement delegation of this call?

I think this has something to do with subscriptand range(or maybe sequence?), But I was unlucky having crossed the intersection of these two topics.

+4
source share
1 answer

deck[0..<5] Sliceable, , , CollectionType SequenceType.

MutableCollectionType, :

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]
        }
    }
}

:

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

, , Int .

. , , .

+7

All Articles