首页 > 解决方案 > 具有关联类型的通用键值存储

问题描述

我想为我的应用程序设计一个键/值配置存储。

我正在尝试提出ConfigurationStore允许我从中心位置设置和获取配置值的协议(在这种情况下可以是地图)。需要对特定键的值进行类型检查。例如:值timeInSeconds不能是String

// psuedocode
protocol ConfigurationStore {

    set(key: TypeCheckedKey, value: AssociatedValueForThatKey)

    get(key: TypeCheckedKey) -> AssociatedValueForThatKey?

}

需要对键及其关联值进行类型检查。例如。我不应该能够为具有 2 种不同值类型的同一个键调用 set。可能需要某种类型的 Key:ValueType 对的映射。

我该怎么做呢?我目前想支持Int,DoubleString配置值

我考虑过使用枚举作为键,但是我可以将多个值类型设置为同一个键。

所有这些都需要通用,以便应用程序的使用者可以定义键和值。

标签: swift

解决方案


尝试这个:

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
    }
}

推荐阅读