How to declare Dictionary<String, Decimal> complies to protocol

◇◆丶佛笑我妖孽 提交于 2020-01-17 06:51:34

问题


I've defined a protocol:

public protocol VariableTable {
    subscript(key:String) -> Decimal? { get set }
}

which merely indicates that a VariableTable has to provide a subscript operator for String->Decimal.

Obviously, Dictionary<String, Decimal> meets that requirement. How do I let the compiler know that?

extension Dictionary<String, Decimal> : VariableTable {}

yields:

Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause

where as:

extension Dictionary : VariableTable where Key == String, Value == Decimal {}

or:

 extension Dictionary : VariableTable where Element == (String, Decimal) {}

result in an error:

Extension of type 'Dictionary' with constraints cannot have an inheritance clause

回答1:


This is not possible in Swift 3.0.

But if all you care about is having this VariableTable subscript you can wrap the dictionary in another type conforming to the the protocol like:

public protocol VariableTableProtocol {
    subscript(key:String) -> Decimal? { get set }
}

final class VariableTable: VariableTableProtocol {
    fileprivate var dictionary: [String: Decimal] = [:]

    subscript(key: String) -> Decimal? {
       get {
           return dictionary[key]
       }
       set {
          dictionary[key] = newValue
       }
    }
}


来源:https://stackoverflow.com/questions/43665217/how-to-declare-dictionarystring-decimal-complies-to-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!