如何快速将呼叫委托给 [0..<n]?

How do I delegate a call to [0..lt;n] in swift?(如何快速将呼叫委托给 [0..lt;n]?)

本文介绍了如何快速将呼叫委托给 [0..<n]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

为方便起见,我使用了这个别名:

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
}

我可以将我的大部分调用委托给 self.deck,但是在谷歌搜索之后,我仍然无法弄清楚如何委托这个调用:

I am able to delegate most of my calls through to self.deck, but after googling around somewhat, I am still having trouble figuring out how to delegate this call:

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

问题

如何实现这个调用的委托?

我认为它与 subscriptrange(或者可能是 sequence?)有关,但我在谷歌搜索交叉点时运气不佳这两个主题.

I think it has something to do with subscript and range (or maybe sequence?), but I had no luck googling the intersection of these two topics.

推荐答案

对于 deck[0..<5] 需要实现 Sliceable 协议,该协议反过来需要 CollectionTypeSequenceType.

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

以下示例实现 MutableCollectionType 以便 设置元素也被转发到数组:

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

然后它就起作用了:

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

类型别名不是绝对必要的,但它们更容易区分 Int 是用作数组元素的类型还是用作数组索引的类型.

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..&lt;n]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何快速将呼叫委托给 [0..&lt;n]?

基础教程推荐