How do I delegate a call to [0..lt;n] in swift?(如何快速将呼叫委托给 [0..lt;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
问题
如何实现这个调用的委托?
我认为它与 subscript
和 range
(或者可能是 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
协议,该协议反过来需要 CollectionType
和 SequenceType
.
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..<n]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何快速将呼叫委托给 [0..<n]?
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01