swift - 具有关联类型的通用键值存储
问题描述
我想为我的应用程序设计一个键/值配置存储。
我正在尝试提出ConfigurationStore
允许我从中心位置设置和获取配置值的协议(在这种情况下可以是地图)。需要对特定键的值进行类型检查。例如:值timeInSeconds
不能是String
// psuedocode
protocol ConfigurationStore {
set(key: TypeCheckedKey, value: AssociatedValueForThatKey)
get(key: TypeCheckedKey) -> AssociatedValueForThatKey?
}
需要对键及其关联值进行类型检查。例如。我不应该能够为具有 2 种不同值类型的同一个键调用 set。可能需要某种类型的 Key:ValueType 对的映射。
我该怎么做呢?我目前想支持Int
,Double
和String
配置值
我考虑过使用枚举作为键,但是我可以将多个值类型设置为同一个键。
所有这些都需要通用,以便应用程序的使用者可以定义键和值。
解决方案
尝试这个:
protocol ConfigurationStore {
associatedtype TypeCheckedKey
associatedtype AssociatedValueWithTheKey
func set(key: TypeCheckedKey, value: AssociatedValueWithTheKey)
func get(key: TypeCheckedKey) -> AssocicatedValueWithTheyKey?
}
升级版:
final class SomeStore: ConfigurationStore {
typealias TypeCheckedKey = String
typealias AssociatedValueWithTheKey = String
func set(key: TypeCheckedKey, value: AssociatedValueWithTheKey) {
// your realisation
}
func get(key: TypeCheckedKey) -> AssocicatedValueWithTheyKey? {
// your realisation
}
}
推荐阅读
- macos - -lgfortran library not found mac(链接器命令失败)
- bash - 删除 BASH 中第一列包含特定字符的行
- reactjs - 如何在 Reactjs 功能组件 history.push 中使用
- android - 如何将 Spinner 设置到 Recyclerview 适配器中
- html - 使背景固定并居中的 div 居中
- r - 根据列表中的 r 和 rbind 文件中的值在列表中创建组
- xamarin - 如何在 Xamarin 表单中使用深色主题浅色主题?
- python - 如何在 Python 中更改二维数组的顺序
- bash - 具有多种分隔符的 bash 脚本中的参数
- html - HTML 和 CSS 图像不会彼此相邻出现(即使使用“浮动”也不会!)