【发布时间】:2016-11-23 14:07:51
【问题描述】:
我已经尝试过extension of Dictionary where <String, AnyObject> 中的解决方案,但它不会为我编译。
我只是想将字典扩展限制为struct 类型。有没有办法做到这一点?
import Cocoa
struct Foo: Hashable {
let bar: String
static let predefinedFoo = Foo(bar: "something")
var hashValue: Int { return bar.hashValue }
public static func ==(lhs: Foo, rhs: Foo) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
struct Baz {
let isSpecial: Bool
}
extension Dictionary where Key: Foo, Value: Baz { // Note that the == syntax does not compile, either
var hasSpecialPredefined: Bool {
return self[.predefinedFoo]?.isSpecial ?? false
}
}
let test: [Foo: Baz] = [.predefinedFoo: Baz(isSpecial: true)]
test.hasSpecialPredefined
使用上面的代码,我得到两个编译错误:
error: type 'Key' constrained to non-protocol type 'Foo'
error: type 'Value' constrained to non-protocol type 'Baz'
error: '[Foo : Baz]' is not convertible to '<<error type>>'
test.hasSpecialPredefined
^~~~
是否可以通过结构来限制扩展?如果不能,为什么不呢?这似乎完全合理。
请注意,这里的
Foo和Bar不在我的控制范围内。它们代表在外部模块中定义的结构,我要扩展的字典也来自这个模块。答案应该假定Foo将始终 是struct,并且该结构将always是字典的键类型。
【问题讨论】:
-
一种方法是简单地创建一个包装器类型,例如 Rob 对this question 的回答。另一种选择是创建一个“虚拟”协议,例如this Q&A
标签: swift generics struct swift-extensions