创建Swift字典子类? [英] Create a Swift Dictionary subclass?

查看:157
本文介绍了创建Swift字典子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以继承 Swift 字典,以便我可以通过我的自定义 / code>到希望普通字典

Can I subclass a Swift Dictionary so that I can pass my custom Dictionary to methods that expect an ordinary Dictionary?

在我的例子中,我想要我的自定义字典

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

推荐答案

Swift词典是结构体,不是类,所以它们不能被子类化。理想情况下,您所使用的方法将被声明为采用适当约束的通用CollectionType(或ExtensibleCollectionType或SequenceType,具体取决于具体情况),而不是具体的Dictionary。

Swift dictionaries are structs, not classes, so they cannot be subclassed. Ideally, the methods you're working with would be declared to take an appropriately constrained generic CollectionType (or ExtensibleCollectionType, or SequenceType, depending on the situation), rather than specifically a Dictionary.

如果这不适合你,无论什么原因,你可以继承NSDictionary,而不是。

If that doesn't work for you for whatever reason, you could subclass NSDictionary instead.

(编辑)和Antonio指出,你可以做扩展字典{...}将一些东西添加到Dictionary结构中,在某些情况下可以替换子类。

(edit) and as Antonio points out, you can do extension Dictionary { … } to add things to the Dictionary struct, which can replace subclassing in some cases.

这篇关于创建Swift字典子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆