David Berry
David Berry

Reputation: 41226

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

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

Upvotes: 0

Views: 332

Answers (1)

Mr. Hedgehog
Mr. Hedgehog

Reputation: 986

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

Upvotes: 1

Related Questions