创建一个Swift Dictionary子类?

问题描述:

我可以继承SwiftDictionary以便我可以将我的自定义Dictionary传递给期望普通Dictionary的方法吗?创建一个Swift Dictionary子类?

编辑

In my case, I want my custom Dictionary to iterate through its keys in insertion-order.

+0

哎哟。这是一个快速的-2。 – 2015-02-23 19:49:46

+1

如果你这样做,我会很感激评论为什么所以我不会再犯同样的错误。 – 2015-02-23 20:04:04

+0

我没有downvote,但如果我猜猜这是因为你没有提供任何代码显示当前的尝试,或者你现在尝试了什么。 – Marcus 2015-02-23 20:05:08

斯威夫特字典是结构体,而不是类,所以它们不能被分类。理想情况下,您正在使用的方法将被声明为采用适当约束的泛型CollectionType(或ExtensibleCollectionType或SequenceType,具体取决于具体情况),而不是特定的Dictionary。

如果由于某种原因无法为您工作,您可以改为NSDictionary的子类。

(编辑)和安东尼奥指出,你可以做扩展字典{...}的东西添加到字典结构,它可以在某些情况下更换子类。

没有,字典和数组在迅速的结构,它不支持继承。 “个性化”字典的唯一方法是使用扩展。

虽然我大部分的意见在这里同意(你不能继承一个Struct设计这是不是一类),你可能会得到你想要的结果与符合CollectionType定制Struct(现更名Collection在雨燕3.0):

struct YourCustomDictionary<Key : Hashable, Value>: Collection { 

    private var elements = Dictionary<Key, Value>() 
    private var keyOrder = Array<Key>() 

    //your custom implementation here 
    //including tracking for your dictionary order 

} 

,使其追加的关键keyOrder阵列您可以重载下标方法。然后提供一个迭代器,它将以正确的顺序返回(Key, Value)元组。

你可能甚至都不需要符合Collection,但这是得到了很多的功能,免费的好方法。

以下是符合集合的结构,它代表字典。根据任何需要修改相当容易。

public struct MyDictionary<Key: Hashable, Value: MyKindOfValue>: Collection { 
    public typealias DictionaryType = Dictionary<Key, Value> 
    private var dictionary: DictionaryType 

    //Collection: these are the access methods 
    public typealias IndexDistance = DictionaryType.IndexDistance 
    public typealias Indices = DictionaryType.Indices 
    public typealias Iterator = DictionaryType.Iterator 
    public typealias SubSequence = DictionaryType.SubSequence 

    public var startIndex: Index { return dictionary.startIndex } 
    public var endIndex: DictionaryType.Index { return dictionary.endIndex } 
    public subscript(position: Index) -> Iterator.Element { return dictionary[position] } 
    public subscript(bounds: Range<Index>) -> SubSequence { return dictionary[bounds] } 
    public var indices: Indices { return dictionary.indices } 
    public subscript(key: Key)->Value? { 
     get { return dictionary[key] } 
     set { dictionary[key] = newValue } 
    } 
    public func index(after i: Index) -> Index { 
     return dictionary.index(after: i) 
    } 

    //Sequence: iteration is implemented here 
    public func makeIterator() -> DictionaryIterator<Key, Value> { 
     return dictionary.makeIterator() 
    } 

    //IndexableBase 
    public typealias Index = DictionaryType.Index 
} 
+0

Swift 3是否正确?我根本无法编译它。是的,我有协议'MyKindOfValue' – 2017-06-27 17:40:48

+0

立即尝试。我加了两个下标和索引。它现在对我来说。原来也是为我编译器(!!),但是如果你看看编译器的错误(在它崩溃之前),你可以推断出错过了什么。 – user3763801 2017-06-27 22:55:11