![](/img/trans.png)
[英]How to create a dictionary with key as a subclass of NSObject and values as an array? Swift
[英]Create a Swift Dictionary subclass?
我可以将Swift
Dictionary
子类化,以便将自定义Dictionary
传递给期望普通Dictionary
吗?
编辑
Swift词典是结构,而不是类,因此它们不能被子类化。 理想情况下,您正在使用的方法将被声明为采用适当约束的通用CollectionType(或ExtensibleCollectionType,或SequenceType,具体取决于具体情况),而不是具体的Dictionary。
如果由于某种原因这对你不起作用,你可以改为继承NSDictionary。
(编辑)正如Antonio指出的那样,你可以做扩展词典{...}来向Dictionary结构添加东西,在某些情况下可以替换子类。
以下是符合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中的字典和数组是结构,不支持继承。 “个性化”字典的唯一方法是使用扩展。
虽然我同意这里的大多数注释(你不能将Struct
子类化,但是设计它不是一个类),你可以使用符合CollectionType
的自定义Struct
获得你想要的结果(现在在Swift 3.0中重命名为Collection
):
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
,但这是免费获得大量功能的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.