使用键和值约束扩展词典

时间:2015-09-28 04:32:46

标签: swift swift-extensions swift-dictionary

我想扩展字典并将其约束为NSDate的特定键类型,其值为Array<MyClass>

MyClass是一个没有子类的快速类。

extension Dictionary where Key: NSDate, Value: Array<MyClass>{
    func myFunction() -> Int{
        // Some thing useful
    }
}

上面的代码返回一个构建错误:

  

键入&#39;价值&#39;约束到非协议类型   &#39;阵列&#39;

好的,似乎它需要被约束到一个特定的协议,但奇怪的是当我将Value约束为:

  

扩展词典其中键:NSDate,值:   MyClass的

编译器不会抱怨并且构建成功。但MyClass不是一个协议。那是什么给出了什么?

我设法像这样限制它:

extension Dictionary where Key: NSDate, Value: CollectionType, Value.Generator.Element: MyClass{
    func myFunction() -> Int{
        var count = 0
        for (_, graphicItemArray) in self{
            count+= (graphicItemArray as! [MyClass]).count
        }

        return count
    }
}

但这需要强制转换,因为我需要以Integer形式获取count属性。

那么为什么我不能明确地将它约束为[MyClass]的值类型?

1 个答案:

答案 0 :(得分:1)

无法对结构使用where子句可能是错误的。检查language reference for where clauses并进入

conformance-requirement → type-identifier­ | ...

似乎type-identifier似乎应该接受struct,即使他们使用的示例是Int

这可能是提交bug的原因。

与您的特定问题相关,如果您使用_ArrayType这是Array实现的协议并且具有您需要的方法,它似乎有效。

extension Dictionary where Key: NSDate, Value: _ArrayType ...

我不确定是否使用这种内部协议会标记您的应用并使其无法通过Apple审核。

相关问题