约束字典的协议扩展

问题描述 投票:3回答:1

我正在尝试获取特定的Dictionary类型以符合协议。

typealias FirebaseDictionary = Dictionary<String, FirebaseValue>

我想符合FirebaseValue协议

protocol FirebaseValue {
    // stuff here
}

我试过这个

extension FirebaseDictionary: FirebaseValue {

}

但我得到一个错误Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause。所以我现在有这个

extension Dictionary where Key == String, Value == FirebaseValue {

}

但是,如果可能的话,我无法弄清楚使其符合协议的正确语法。如果不可能,还有其他方法可以达到同样的效果吗?我试图只允许特定类型进入属性,并且能够在回读时轻松识别它们的类型。

This question was asked但没有给出确定的答案,而且无论如何都可能有所改变

swift dictionary generics swift-protocols swift-dictionary
1个回答
1
投票

从Swift 4.2开始,你可以这样做:

extension Dictionary : FirebaseValue where Key == String, Value == FirebaseValue {
}
© www.soinside.com 2019 - 2024. All rights reserved.