是否可以指定字典中允许的对象类型? [英] Is it possible to specify the object type allowed in a Dictionary?

查看:70
本文介绍了是否可以指定字典中允许的对象类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3.x中可以指定字典中允许的对象类型吗?

In Swift 3.x is it possible to specify the object type allowed in a Dictionary?

如果在声明时我们可以传递一组

It would be great if at declaration time we could pass a set of object types allowed.

推荐答案

您可以通过自定义协议来实现此目的,该协议仅由要允许的对象类型实现。字典:

You can achieve this via a custom protocol that is implemented only by the types you want to allow within the dictionary:

protocol AllowedDictionaryValue: {}

extension String: AllowedDictionaryValue {}
extension Int: AllowedDictionaryValue {}
extension MyClass: AllowedDictionaryValue {}
extension MyEnum: AllowedDictionaryValue {}

let dictionary: [String:AllowedDictionaryValue] = ...

以上字典仅包含 String Int MyClass 实例和 MyEnum 值。

The above dictionary will hold only String's, Int's, MyClass instances, and MyEnum values.

这样,您可以在字典中只保留想要的值,同时保持字典的异构性。

This way you can have only the values you want in the dictionary, while keeping the dictionary heterogenous.

这篇关于是否可以指定字典中允许的对象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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