swift - 约束字典的协议(protocol)扩展

标签 swift dictionary generics swift-protocols swift-dictionary

我正在尝试让特定的字典类型符合协议(protocol)。

typealias FirebaseDictionary = Dictionary<String, FirebaseValue>

我希望符合 FirebaseValue 协议(protocol)

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 {

}

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

This question was asked但没有给出明确的答案,无论如何它可能已经改变

最佳答案

从 Swift 4.2 开始,您可以使用:

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

关于swift - 约束字典的协议(protocol)扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663049/

相关文章:

ios - 使用 Accelerate 平均像素颜色

xcode - 存档提交失败,出现错误

ios - 仅在 tableview 单元格中制作左下角

python - 使用 python 从多个列表中嵌套字典

python - 如何在 snakemake 的扩展函数参数中使用通配符?

c# - 反射:将反射类型转换为泛型,类型为字符串并对其进行迭代

xcode - 您如何使用 swift 使用 xcode 6 在 iOS 中以编程方式创建有组织的相册?

c# - 在 C# : How to ensure methods in the base class return the derived class's type? 的基类中使用泛型

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

python - 在 Python 的列表中对嵌套字典进行排序?