如何声明Dictionary< String,Decimal>符合协议 [英] How to declare Dictionary<String, Decimal> complies to protocol

查看:181
本文介绍了如何声明Dictionary< String,Decimal>符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个协议:

I've defined a protocol:

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

仅表示VariableTable必须为String-> Decimal提供下标运算符.

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

很显然,Dictionary<String, Decimal>符合该要求.如何让编译器知道这一点?

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

extension Dictionary<String, Decimal> : VariableTable {}

产量:

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

其中:

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

或:

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

导致错误:

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

推荐答案

在Swift 3.0中是不可能的.

This is not possible in Swift 3.0.

但是,如果您只关心具有此VariableTable下标,则可以将字典包装为符合以下协议的另一种类型:

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

这篇关于如何声明Dictionary&lt; String,Decimal&gt;符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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