我可以繼承Swift
Dictionary
以便我可以將我的自定義Dictionary
傳遞給期望普通Dictionary
的方法嗎?創建一個Swift Dictionary子類?
編輯
In my case, I want my custom Dictionary
to iterate through its keys in insertion-order.
我可以繼承Swift
Dictionary
以便我可以將我的自定義Dictionary
傳遞給期望普通Dictionary
的方法嗎?創建一個Swift Dictionary子類?
編輯
In my case, I want my custom Dictionary
to iterate through its keys in insertion-order.
斯威夫特字典是結構體,而不是類,所以它們不能被分類。理想情況下,您正在使用的方法將被聲明爲採用適當約束的泛型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
}
Swift 3是否正確?我根本無法編譯它。是的,我有協議'MyKindOfValue' – 2017-06-27 17:40:48
立即嘗試。我加了兩個下標和索引。它現在對我來說。原來也是爲我編譯器(!!),但是如果你看看編譯器的錯誤(在它崩潰之前),你可以推斷出錯過了什麼。 – user3763801 2017-06-27 22:55:11
哎喲。這是一個快速的-2。 – 2015-02-23 19:49:46
如果你這樣做,我會很感激評論爲什麼所以我不會再犯同樣的錯誤。 – 2015-02-23 20:04:04
我沒有downvote,但如果我猜猜這是因爲你沒有提供任何代碼顯示當前的嘗試,或者你現在嘗試了什麼。 – Marcus 2015-02-23 20:05:08