问题描述
我有一个容器类,它有一个基础字典。我已经为这个类实现了下标来访问底层字典的成员。现在,我正在尝试在这个类上创建一个序列,这样我就可以通过在类实例本身上使用'for-in'循环来迭代底层字典的所有元素。我一直在寻找一些序列为Swift词典的例子,但找不到任何能很好地解释这些东西的东西。我已经看到了Swift数组的一些自定义序列示例,但没有看到Swift Dictionary的自定义序列示例。如果有人能解释我是如何实现这一点的,我真的很感激。以下是该类的代码(没有序列代码,因为我不知道从哪里开始)
I have a container class that has an underlying dictionary. I have implemented subscripts for this class to access member of the underlying dictionary. Now, I am trying to create a sequence on this class so that I could iterate over all the elements of the underlying dictionary by using 'for-in' loop on the class instance itself. I have been looking to find some examples for Sequences for Swift Dictionary but could not find anything that explains the stuff well. I have seen some custom sequence examples for Swift Array but none for the Swift Dictionary. I would really appreciate if anyone could explain how I can achieve that. Following is the code for the class (no sequence code yet as I am not sure where to begin)
import Foundation
class STCQuestionList : GeneratorType, SequenceType {
private var questionDict: [String : STCQuestion] = [ : ];
subscript(key : String?) -> STCQuestion? {
get {
if (key != nil) {
return self.questionDict[key!];
}
return nil;
}
set(newValue) {
if (key != nil) {
self.questionDict[key!] = newValue;
}
}
}
func generate() -> GeneratorType {
}
func next() -> (String, STCQuestion)? {
if (self.questionDict.isEmpty) {
return .None
}
}
}
推荐答案
如果我理解正确,那么转发生成怎么样?
If I'm understanding correctly, how about just forwarding on the generate?
func generate() -> DictionaryGenerator<String, STCQuestion> {
return questionDict.generate()
}
(你不是需要实现 GeneratorType
,只需 SequenceType
就可以了。它是 generate()
本身返回 GeneratorType
, 必须实现的内容 next()
,字典中现有的 generate()
实现已经为你做了。)
(You don't need to implement GeneratorType
, just SequenceType
should do. It's generate()
itself that returns a GeneratorType
, and that's what has to implement next()
, which the existing generate()
implementation in Dictionary already does for you.)
完整的工作示例根据您的代码:
Full worked example based on your code:
// Playground - noun: a place where people can play
import Foundation
class STCQuestion {
let foo: String
init(_ foo: String) {
self.foo = foo
}
}
class STCQuestionList : SequenceType {
private var questionDict: [String : STCQuestion] = [ : ];
subscript(key : String?) -> STCQuestion? {
get {
if key != nil {
return self.questionDict[key!];
}
return nil;
}
set(newValue) {
if key != nil {
self.questionDict[key!] = newValue;
}
}
}
func generate() -> DictionaryGenerator<String, STCQuestion> {
return questionDict.generate()
}
}
var list = STCQuestionList()
list["test"] = STCQuestion("blah")
list["another"] = STCQuestion("wibble")
list["third"] = STCQuestion("doodah")
for (key, value) in list {
println("Key: \(key) Foo: \(value.foo)")
}
// Output:
// Key: test Foo: blah
// Key: another Foo: wibble
// Key: third Foo: doodah
这篇关于Swift Dictionary的自定义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!